Google Cloud Key Management Service client library for managing cryptographic keys in the cloud
npx @tessl/cli install tessl/pypi-google-cloud-kms@3.5.00
# Google Cloud KMS
1
2
Google Cloud Key Management Service (KMS) client library for Python that enables developers to manage cryptographic keys in the cloud with the same ease as on-premises systems. It provides comprehensive support for symmetric and asymmetric encryption, digital signing, MAC operations, key lifecycle management, external key management, and automated key provisioning through Google's Cloud KMS service.
3
4
## Package Information
5
6
- **Package Name**: google-cloud-kms
7
- **Language**: Python
8
- **Installation**: `pip install google-cloud-kms`
9
- **Version**: 3.5.1
10
11
## Core Imports
12
13
```python
14
from google.cloud import kms
15
```
16
17
Alternative version-specific import:
18
19
```python
20
from google.cloud import kms_v1
21
```
22
23
## Basic Usage
24
25
```python
26
from google.cloud import kms
27
28
# Initialize the Key Management Service client
29
client = kms.KeyManagementServiceClient()
30
31
# Create a key ring
32
project_id = "your-project-id"
33
location_id = "global"
34
key_ring_id = "example-keyring"
35
36
# Format the parent name
37
location_name = f"projects/{project_id}/locations/{location_id}"
38
39
# Create key ring
40
key_ring = {}
41
key_ring_name = client.create_key_ring(
42
request={
43
"parent": location_name,
44
"key_ring_id": key_ring_id,
45
"key_ring": key_ring,
46
}
47
)
48
49
# Create a crypto key
50
crypto_key_id = "example-key"
51
purpose = kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT
52
crypto_key = {
53
"purpose": purpose,
54
}
55
56
crypto_key_name = client.create_crypto_key(
57
request={
58
"parent": key_ring_name.name,
59
"crypto_key_id": crypto_key_id,
60
"crypto_key": crypto_key,
61
}
62
)
63
64
# Encrypt data
65
plaintext = b"Hello, World!"
66
encrypt_response = client.encrypt(
67
request={
68
"name": crypto_key_name.name,
69
"plaintext": plaintext,
70
}
71
)
72
73
# Decrypt data
74
decrypt_response = client.decrypt(
75
request={
76
"name": crypto_key_name.name,
77
"ciphertext": encrypt_response.ciphertext,
78
}
79
)
80
81
print(f"Decrypted: {decrypt_response.plaintext.decode('utf-8')}")
82
```
83
84
## Architecture
85
86
Google Cloud KMS provides a comprehensive cryptographic key management system built on Google's infrastructure:
87
88
- **Service Clients**: High-level client interfaces (KeyManagementServiceClient, AutokeyClient, etc.)
89
- **Resource Hierarchy**: KeyRings contain CryptoKeys, which have CryptoKeyVersions
90
- **Cryptographic Operations**: Encrypt/decrypt, sign/verify, MAC operations using managed keys
91
- **Protection Levels**: Software, HSM, and external key manager options
92
- **Lifecycle Management**: Automated key rotation, destruction scheduling, and recovery
93
- **Integration**: Seamless integration with Google Cloud IAM, audit logging, and VPC
94
95
## Capabilities
96
97
### Key Management Service
98
99
Core key and cryptographic operations including key ring management, crypto key lifecycle, encryption/decryption, asymmetric signing, and MAC operations. This is the primary interface for most KMS operations.
100
101
```python { .api }
102
class KeyManagementServiceClient:
103
def create_key_ring(self, request: CreateKeyRingRequest) -> KeyRing: ...
104
def create_crypto_key(self, request: CreateCryptoKeyRequest) -> CryptoKey: ...
105
def encrypt(self, request: EncryptRequest) -> EncryptResponse: ...
106
def decrypt(self, request: DecryptRequest) -> DecryptResponse: ...
107
def asymmetric_sign(self, request: AsymmetricSignRequest) -> AsymmetricSignResponse: ...
108
def generate_random_bytes(self, request: GenerateRandomBytesRequest) -> GenerateRandomBytesResponse: ...
109
```
110
111
[Key Management Service](./key-management-service.md)
112
113
### Autokey Service
114
115
Automated key provisioning for Customer-Managed Encryption Keys (CMEK) that creates and manages keys automatically based on resource needs. Includes both key handle management and administrative configuration.
116
117
```python { .api }
118
class AutokeyClient:
119
def create_key_handle(self, request: CreateKeyHandleRequest) -> KeyHandle: ...
120
def get_key_handle(self, request: GetKeyHandleRequest) -> KeyHandle: ...
121
def list_key_handles(self, request: ListKeyHandlesRequest) -> ListKeyHandlesResponse: ...
122
123
class AutokeyAdminClient:
124
def update_autokey_config(self, request: UpdateAutokeyConfigRequest) -> AutokeyConfig: ...
125
def get_autokey_config(self, request: GetAutokeyConfigRequest) -> AutokeyConfig: ...
126
```
127
128
[Autokey Service](./autokey-service.md)
129
130
### External Key Management
131
132
Integration with external key management systems (EKM) for keys stored and managed outside of Google Cloud, supporting both VPC and direct connection patterns.
133
134
```python { .api }
135
class EkmServiceClient:
136
def create_ekm_connection(self, request: CreateEkmConnectionRequest) -> EkmConnection: ...
137
def get_ekm_connection(self, request: GetEkmConnectionRequest) -> EkmConnection: ...
138
def verify_connectivity(self, request: VerifyConnectivityRequest) -> VerifyConnectivityResponse: ...
139
def update_ekm_config(self, request: UpdateEkmConfigRequest) -> EkmConfig: ...
140
```
141
142
[External Key Management](./external-key-management.md)
143
144
### Types and Enums
145
146
Comprehensive type system including resource types (CryptoKey, KeyRing, CryptoKeyVersion), request/response objects, enums for algorithms and states, and configuration options.
147
148
```python { .api }
149
class CryptoKey:
150
purpose: CryptoKeyPurpose
151
version_template: CryptoKeyVersionTemplate
152
153
class CryptoKeyVersion:
154
algorithm: CryptoKeyVersionAlgorithm
155
state: CryptoKeyVersionState
156
157
class ProtectionLevel(Enum):
158
SOFTWARE = 1
159
HSM = 2
160
EXTERNAL = 3
161
```
162
163
[Types and Enums](./types-and-enums.md)
164
165
## Client Configuration
166
167
All service clients support flexible configuration for authentication, endpoints, and transport options.
168
169
### Authentication Methods
170
171
```python
172
from google.cloud import kms
173
174
# Using Application Default Credentials (recommended)
175
client = kms.KeyManagementServiceClient()
176
177
# Using service account file
178
client = kms.KeyManagementServiceClient.from_service_account_file(
179
"path/to/service-account-key.json"
180
)
181
182
# Using service account info dictionary
183
service_account_info = {
184
"type": "service_account",
185
"project_id": "your-project-id",
186
"private_key_id": "key-id",
187
"private_key": "-----BEGIN PRIVATE KEY-----\n...",
188
"client_email": "service-account@your-project.iam.gserviceaccount.com",
189
"client_id": "client-id",
190
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
191
"token_uri": "https://oauth2.googleapis.com/token"
192
}
193
194
client = kms.KeyManagementServiceClient.from_service_account_info(service_account_info)
195
```
196
197
### Client Options and Transport Configuration
198
199
```python
200
from google.cloud import kms
201
from google.api_core import client_options
202
203
# Custom endpoint configuration
204
options = client_options.ClientOptions(
205
api_endpoint="https://custom-kms-endpoint.googleapis.com"
206
)
207
client = kms.KeyManagementServiceClient(client_options=options)
208
209
# Universe domain configuration (for multi-tenant scenarios)
210
options = client_options.ClientOptions(
211
universe_domain="custom.universe.domain"
212
)
213
client = kms.KeyManagementServiceClient(client_options=options)
214
215
# Transport configuration with custom gRPC channel
216
from google.api_core import grpc_helpers
217
import grpc
218
219
channel = grpc_helpers.create_channel(
220
target="kms.googleapis.com:443",
221
credentials=None,
222
options=[
223
("grpc.keepalive_time_ms", 30000),
224
("grpc.keepalive_timeout_ms", 5000),
225
]
226
)
227
228
client = kms.KeyManagementServiceClient(transport="grpc", channel=channel)
229
```
230
231
### Context Manager Usage
232
233
```python
234
# Automatic resource cleanup using context manager
235
with kms.KeyManagementServiceClient() as client:
236
# Create resources
237
key_ring = client.create_key_ring(request={
238
"parent": f"projects/{project_id}/locations/{location_id}",
239
"key_ring_id": "example-keyring",
240
"key_ring": {},
241
})
242
243
# Use resources
244
crypto_key = client.create_crypto_key(request={
245
"parent": key_ring.name,
246
"crypto_key_id": "example-key",
247
"crypto_key": {
248
"purpose": kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT,
249
},
250
})
251
252
# Client resources automatically cleaned up here
253
```
254
255
### Client Properties
256
257
```python
258
client = kms.KeyManagementServiceClient()
259
260
# Access client configuration
261
print(f"API Endpoint: {client.api_endpoint}")
262
print(f"Universe Domain: {client.universe_domain}")
263
264
# Access transport layer
265
transport = client.transport
266
print(f"Transport Type: {type(transport)}")
267
```
268
269
## Common Client Features
270
271
All service clients provide:
272
273
**Authentication and Configuration:**
274
- Service account authentication via JSON key files or application default credentials
275
- Custom endpoint configuration for private Google Access or testing
276
- Universe domain configuration for multi-tenant scenarios
277
278
**IAM Integration:**
279
- `get_iam_policy()`, `set_iam_policy()`, `test_iam_permissions()` for fine-grained access control
280
- Integration with Google Cloud IAM roles and permissions
281
282
**Operations and Location Support:**
283
- Long-running operation management via `get_operation()`
284
- Multi-region support via `list_locations()` and `get_location()`
285
- Path helper methods for constructing resource names
286
287
**Client Lifecycle:**
288
- Context manager support for automatic resource cleanup
289
- Async client variants for all service clients
290
- Transport customization (gRPC, REST) with configurable timeouts and retries