0
# Key Management
1
2
Core key lifecycle operations including creation, retrieval, updating, deletion, and enumeration of cryptographic keys in Azure Key Vault. Supports all Azure Key Vault key types (RSA, EC, symmetric) with both hardware-protected (HSM) and software-protected variants.
3
4
## Capabilities
5
6
### Key Creation
7
8
Create new cryptographic keys with various types and configurations.
9
10
```python { .api }
11
def create_key(
12
name: str,
13
key_type: KeyType,
14
*,
15
size: int = None,
16
curve: KeyCurveName = None,
17
key_operations: List[KeyOperation] = None,
18
enabled: bool = None,
19
not_before: datetime = None,
20
expires_on: datetime = None,
21
tags: Dict[str, str] = None,
22
**kwargs
23
) -> KeyVaultKey:
24
"""
25
Create a new key.
26
27
Parameters:
28
- name: The name of the key to create
29
- key_type: The type of key to create (RSA, EC, oct, etc.)
30
- size: Key size in bits (RSA: 2048, 3072, 4096; oct: 128, 192, 256)
31
- curve: Elliptic curve for EC keys (P-256, P-384, P-521, P-256K)
32
- key_operations: List of permitted operations
33
- enabled: Whether the key is enabled
34
- not_before: Key not valid before this date
35
- expires_on: Key expiration date
36
- tags: Application-specific metadata
37
38
Returns:
39
KeyVaultKey: The created key with metadata
40
"""
41
42
def create_rsa_key(
43
name: str,
44
*,
45
size: int = None,
46
hardware_protected: bool = False,
47
key_operations: List[KeyOperation] = None,
48
enabled: bool = None,
49
not_before: datetime = None,
50
expires_on: datetime = None,
51
tags: Dict[str, str] = None,
52
**kwargs
53
) -> KeyVaultKey:
54
"""
55
Create an RSA key.
56
57
Parameters:
58
- name: The name of the key to create
59
- size: RSA key size in bits (2048, 3072, 4096). Default: 2048
60
- hardware_protected: Whether to use HSM-backed key (RSA-HSM)
61
- key_operations: List of permitted operations
62
- enabled: Whether the key is enabled
63
- not_before: Key not valid before this date
64
- expires_on: Key expiration date
65
- tags: Application-specific metadata
66
67
Returns:
68
KeyVaultKey: The created RSA key
69
"""
70
71
def create_ec_key(
72
name: str,
73
*,
74
curve: KeyCurveName = None,
75
hardware_protected: bool = False,
76
key_operations: List[KeyOperation] = None,
77
enabled: bool = None,
78
not_before: datetime = None,
79
expires_on: datetime = None,
80
tags: Dict[str, str] = None,
81
**kwargs
82
) -> KeyVaultKey:
83
"""
84
Create an Elliptic Curve key.
85
86
Parameters:
87
- name: The name of the key to create
88
- curve: Elliptic curve (P-256, P-384, P-521, P-256K). Default: P-256
89
- hardware_protected: Whether to use HSM-backed key (EC-HSM)
90
- key_operations: List of permitted operations
91
- enabled: Whether the key is enabled
92
- not_before: Key not valid before this date
93
- expires_on: Key expiration date
94
- tags: Application-specific metadata
95
96
Returns:
97
KeyVaultKey: The created EC key
98
"""
99
100
def create_oct_key(
101
name: str,
102
*,
103
size: int = None,
104
hardware_protected: bool = False,
105
key_operations: List[KeyOperation] = None,
106
enabled: bool = None,
107
not_before: datetime = None,
108
expires_on: datetime = None,
109
tags: Dict[str, str] = None,
110
**kwargs
111
) -> KeyVaultKey:
112
"""
113
Create a symmetric (oct) key.
114
115
Parameters:
116
- name: The name of the key to create
117
- size: Key size in bits (128, 192, 256). Default: 256
118
- hardware_protected: Whether to use HSM-backed key (oct-HSM)
119
- key_operations: List of permitted operations
120
- enabled: Whether the key is enabled
121
- not_before: Key not valid before this date
122
- expires_on: Key expiration date
123
- tags: Application-specific metadata
124
125
Returns:
126
KeyVaultKey: The created symmetric key
127
"""
128
```
129
130
#### Usage Examples
131
132
```python
133
from azure.keyvault.keys import KeyClient, KeyType, KeyCurveName, KeyOperation
134
from azure.identity import DefaultAzureCredential
135
136
client = KeyClient(vault_url="https://vault.vault.azure.net/", credential=DefaultAzureCredential())
137
138
# Create RSA key with specific operations
139
rsa_key = client.create_rsa_key(
140
"my-rsa-key",
141
size=2048,
142
key_operations=[KeyOperation.encrypt, KeyOperation.decrypt, KeyOperation.sign, KeyOperation.verify]
143
)
144
145
# Create EC key for signing
146
ec_key = client.create_ec_key(
147
"my-ec-key",
148
curve=KeyCurveName.p_256,
149
key_operations=[KeyOperation.sign, KeyOperation.verify]
150
)
151
152
# Create symmetric key for encryption
153
symmetric_key = client.create_oct_key(
154
"my-symmetric-key",
155
size=256,
156
key_operations=[KeyOperation.encrypt, KeyOperation.decrypt]
157
)
158
```
159
160
### Key Retrieval
161
162
Retrieve existing keys and their properties.
163
164
```python { .api }
165
def get_key(name: str, version: str = None, **kwargs) -> KeyVaultKey:
166
"""
167
Get a key from the vault.
168
169
Parameters:
170
- name: The name of the key to retrieve
171
- version: Specific version of the key (optional, gets latest if omitted)
172
173
Returns:
174
KeyVaultKey: The key with its properties and cryptographic material
175
"""
176
177
def list_properties_of_keys(**kwargs) -> ItemPaged[KeyProperties]:
178
"""
179
List properties of all keys in the vault.
180
181
Returns:
182
ItemPaged[KeyProperties]: Paginated list of key properties (without cryptographic material)
183
"""
184
185
def list_properties_of_key_versions(name: str, **kwargs) -> ItemPaged[KeyProperties]:
186
"""
187
List properties of all versions of a specific key.
188
189
Parameters:
190
- name: The name of the key
191
192
Returns:
193
ItemPaged[KeyProperties]: Paginated list of key version properties
194
"""
195
```
196
197
#### Usage Examples
198
199
```python
200
# Get latest version of a key
201
key = client.get_key("my-key")
202
print(f"Key ID: {key.id}")
203
print(f"Key Type: {key.key_type}")
204
205
# Get specific version of a key
206
specific_key = client.get_key("my-key", version="abc123...")
207
208
# List all keys in the vault
209
for key_properties in client.list_properties_of_keys():
210
print(f"Key: {key_properties.name}, Enabled: {key_properties.enabled}")
211
212
# List all versions of a specific key
213
for version_properties in client.list_properties_of_key_versions("my-key"):
214
print(f"Version: {version_properties.version}, Created: {version_properties.created_on}")
215
```
216
217
### Key Updates
218
219
Update key properties and metadata.
220
221
```python { .api }
222
def update_key_properties(
223
name: str,
224
version: str = None,
225
*,
226
key_operations: List[KeyOperation] = None,
227
enabled: bool = None,
228
not_before: datetime = None,
229
expires_on: datetime = None,
230
tags: Dict[str, str] = None,
231
**kwargs
232
) -> KeyVaultKey:
233
"""
234
Update a key's properties.
235
236
Parameters:
237
- name: The name of the key to update
238
- version: Specific version to update (optional, updates latest if omitted)
239
- key_operations: New list of permitted operations
240
- enabled: Whether the key should be enabled
241
- not_before: New not-before date
242
- expires_on: New expiration date
243
- tags: New application-specific metadata
244
245
Returns:
246
KeyVaultKey: The updated key
247
"""
248
```
249
250
#### Usage Examples
251
252
```python
253
# Disable a key
254
updated_key = client.update_key_properties("my-key", enabled=False)
255
256
# Update key operations
257
updated_key = client.update_key_properties(
258
"my-key",
259
key_operations=[KeyOperation.sign, KeyOperation.verify]
260
)
261
262
# Add tags and expiration
263
from datetime import datetime, timedelta
264
updated_key = client.update_key_properties(
265
"my-key",
266
tags={"environment": "production", "team": "security"},
267
expires_on=datetime.utcnow() + timedelta(days=365)
268
)
269
```
270
271
### Key Deletion
272
273
Delete keys with soft-delete protection.
274
275
```python { .api }
276
def begin_delete_key(name: str, **kwargs) -> LROPoller[DeletedKey]:
277
"""
278
Begin deleting a key (soft delete).
279
280
Parameters:
281
- name: The name of the key to delete
282
283
Returns:
284
LROPoller[DeletedKey]: Long-running operation poller for the deletion
285
"""
286
```
287
288
#### Usage Examples
289
290
```python
291
# Delete a key (soft delete)
292
delete_poller = client.begin_delete_key("my-key")
293
deleted_key = delete_poller.result()
294
print(f"Deleted key: {deleted_key.name}")
295
print(f"Recovery ID: {deleted_key.recovery_id}")
296
print(f"Scheduled purge date: {deleted_key.scheduled_purge_date}")
297
```
298
299
### Utility Operations
300
301
Additional key management utilities.
302
303
```python { .api }
304
def get_random_bytes(count: int, **kwargs) -> bytes:
305
"""
306
Get cryptographically secure random bytes from the Key Vault HSM.
307
308
Parameters:
309
- count: Number of random bytes to retrieve (1-128)
310
311
Returns:
312
bytes: Cryptographically secure random bytes
313
"""
314
315
def get_cryptography_client(
316
key_name: str,
317
*,
318
key_version: str = None,
319
**kwargs
320
) -> CryptographyClient:
321
"""
322
Get a CryptographyClient for performing cryptographic operations with a specific key.
323
324
Parameters:
325
- key_name: Name of the key to use for cryptographic operations
326
- key_version: Specific version of the key (optional)
327
328
Returns:
329
CryptographyClient: Client for cryptographic operations
330
"""
331
```
332
333
#### Usage Examples
334
335
```python
336
# Get random bytes
337
random_data = client.get_random_bytes(32)
338
print(f"Random bytes: {random_data.hex()}")
339
340
# Get crypto client for a key
341
crypto_client = client.get_cryptography_client("my-encryption-key")
342
```
343
344
### Key Attestation
345
346
Get attestation information for hardware security module (HSM) backed keys.
347
348
```python { .api }
349
def get_key_attestation(
350
name: str,
351
version: str = None,
352
**kwargs
353
) -> KeyVaultKey:
354
"""
355
Get attestation information for a key.
356
357
Parameters:
358
- name: The name of the key
359
- version: Specific version of the key (optional, gets latest if omitted)
360
361
Returns:
362
KeyVaultKey: The key with attestation information populated
363
364
Raises:
365
- ResourceNotFoundError: If the key doesn't exist
366
- ForbiddenError: If insufficient permissions to access attestation
367
"""
368
```
369
370
#### Usage Examples
371
372
```python
373
# Get key attestation
374
key_with_attestation = client.get_key_attestation("my-hsm-key")
375
if key_with_attestation.properties.attestation:
376
print(f"Attestation version: {key_with_attestation.properties.attestation.version}")
377
print(f"Certificate available: {key_with_attestation.properties.attestation.certificate_pem_file is not None}")
378
379
# Get attestation for specific version
380
specific_attestation = client.get_key_attestation("my-hsm-key", version="abc123...")
381
```
382
383
## Types
384
385
```python { .api }
386
class KeyVaultKey:
387
"""A key's attributes and cryptographic material."""
388
id: str
389
name: str
390
properties: KeyProperties
391
key: JsonWebKey
392
key_type: KeyType
393
key_operations: List[KeyOperation]
394
395
class KeyAttestation:
396
"""Key attestation information for HSM-backed keys."""
397
certificate_pem_file: bytes # Certificate used for attestation validation (PEM format)
398
private_key_attestation: bytes # Private key attestation
399
public_key_attestation: bytes # Public key attestation
400
version: str # Attestation version
401
402
class KeyVaultKeyIdentifier:
403
"""Information about a KeyVaultKey parsed from a key ID."""
404
source_id: str # The complete key identifier URL
405
vault_url: str # The Key Vault URL
406
name: str # The key name
407
version: str # The key version (optional)
408
409
class KeyProperties:
410
"""A key's ID and attributes without cryptographic material."""
411
id: str
412
name: str
413
version: str
414
enabled: bool
415
not_before: datetime
416
expires_on: datetime
417
created_on: datetime
418
updated_on: datetime
419
vault_url: str
420
recoverable_days: int
421
recovery_level: str
422
tags: Dict[str, str]
423
managed: bool
424
exportable: bool
425
426
class JsonWebKey:
427
"""JSON Web Key representation as defined in RFC 7517."""
428
kid: str
429
kty: KeyType
430
key_ops: List[KeyOperation]
431
# RSA parameters
432
n: bytes # RSA modulus
433
e: bytes # RSA public exponent
434
d: bytes # RSA private exponent
435
dp: bytes # RSA private key parameter
436
dq: bytes # RSA private key parameter
437
qi: bytes # RSA private key parameter
438
p: bytes # RSA secret prime
439
q: bytes # RSA secret prime
440
# EC parameters
441
crv: KeyCurveName # Elliptic curve name
442
x: bytes # X component of EC public key
443
y: bytes # Y component of EC public key
444
# Symmetric key parameters
445
k: bytes # Symmetric key
446
# HSM token
447
t: bytes # HSM Token for Bring Your Own Key
448
449
class KeyType(str, Enum):
450
"""Supported key types."""
451
ec = "EC"
452
ec_hsm = "EC-HSM"
453
rsa = "RSA"
454
rsa_hsm = "RSA-HSM"
455
oct = "oct"
456
oct_hsm = "oct-HSM"
457
458
class KeyCurveName(str, Enum):
459
"""Supported elliptic curves."""
460
p_256 = "P-256" # NIST P-256 elliptic curve
461
p_384 = "P-384" # NIST P-384 elliptic curve
462
p_521 = "P-521" # NIST P-521 elliptic curve
463
p_256_k = "P-256K" # SECG SECP256K1 elliptic curve
464
465
class KeyOperation(str, Enum):
466
"""Supported key operations."""
467
encrypt = "encrypt"
468
decrypt = "decrypt"
469
import_key = "import"
470
sign = "sign"
471
verify = "verify"
472
wrap_key = "wrapKey"
473
unwrap_key = "unwrapKey"
474
export = "export"
475
```