Microsoft Azure Key Vault Keys client library for Python providing cryptographic key management operations
npx @tessl/cli install tessl/pypi-azure-keyvault-keys@4.11.00
# Azure Key Vault Keys
1
2
Microsoft Azure Key Vault Keys client library for Python providing comprehensive cryptographic key management operations including creating, storing, retrieving, updating, and deleting cryptographic keys in Azure Key Vault. The library supports various key types (RSA, EC, oct), key operations (encrypt, decrypt, sign, verify, wrap, unwrap), key versioning, and provides both synchronous and asynchronous client implementations.
3
4
## Package Information
5
6
- **Package Name**: azure-keyvault-keys
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install azure-keyvault-keys`
10
- **Version**: Available via `azure.keyvault.keys.__version__`
11
12
## Core Imports
13
14
```python
15
from azure.keyvault.keys import KeyClient
16
```
17
18
For asynchronous operations:
19
20
```python
21
from azure.keyvault.keys.aio import KeyClient
22
```
23
24
For cryptographic operations:
25
26
```python
27
from azure.keyvault.keys.crypto import CryptographyClient
28
from azure.keyvault.keys.crypto.aio import CryptographyClient # async version
29
```
30
31
For data models and enums:
32
33
```python
34
from azure.keyvault.keys import (
35
KeyVaultKey, KeyProperties, DeletedKey, JsonWebKey,
36
KeyType, KeyCurveName, KeyOperation
37
)
38
```
39
40
## Basic Usage
41
42
```python
43
from azure.identity import DefaultAzureCredential
44
from azure.keyvault.keys import KeyClient, KeyType
45
46
# Create a client
47
credential = DefaultAzureCredential()
48
vault_url = "https://my-key-vault.vault.azure.net/"
49
client = KeyClient(vault_url=vault_url, credential=credential)
50
51
# Create a key
52
key_name = "my-rsa-key"
53
key = client.create_rsa_key(key_name, size=2048)
54
print(f"Created key: {key.name}")
55
56
# Get a key
57
retrieved_key = client.get_key(key_name)
58
print(f"Retrieved key: {retrieved_key.name}")
59
60
# Create a cryptography client for operations
61
crypto_client = client.get_cryptography_client(key_name)
62
63
# Encrypt data
64
from azure.keyvault.keys.crypto import EncryptionAlgorithm
65
plaintext = b"Hello, World!"
66
encrypt_result = crypto_client.encrypt(EncryptionAlgorithm.rsa_oaep, plaintext)
67
print(f"Encrypted data length: {len(encrypt_result.ciphertext)}")
68
69
# Decrypt data
70
decrypt_result = crypto_client.decrypt(EncryptionAlgorithm.rsa_oaep, encrypt_result.ciphertext)
71
print(f"Decrypted text: {decrypt_result.plaintext}")
72
```
73
74
## Architecture
75
76
The azure-keyvault-keys package follows a modular architecture with clear separation of concerns:
77
78
- **KeyClient**: Main client for key lifecycle management (create, read, update, delete, list, backup, restore)
79
- **CryptographyClient**: Specialized client for cryptographic operations using keys (encrypt, decrypt, sign, verify, wrap, unwrap)
80
- **Data Models**: Comprehensive type definitions for keys, properties, and operation results
81
- **Enums**: Strongly-typed constants for algorithms, key types, operations, and curves
82
- **Async Support**: Complete async/await implementations parallel to synchronous APIs
83
84
This design enables both high-level key management and low-level cryptographic operations while supporting enterprise features like key rotation, attestation, and Managed HSM integration.
85
86
## Capabilities
87
88
### Key Management
89
90
Core key lifecycle operations including creation, retrieval, updating, deletion, and enumeration. Supports all Azure Key Vault key types (RSA, EC, symmetric) with hardware and software variants.
91
92
```python { .api }
93
def create_key(name: str, key_type: KeyType, **kwargs) -> KeyVaultKey: ...
94
def create_rsa_key(name: str, *, size: int = None, **kwargs) -> KeyVaultKey: ...
95
def create_ec_key(name: str, *, curve: KeyCurveName = None, **kwargs) -> KeyVaultKey: ...
96
def get_key(name: str, version: str = None, **kwargs) -> KeyVaultKey: ...
97
def update_key_properties(name: str, version: str = None, **kwargs) -> KeyVaultKey: ...
98
def begin_delete_key(name: str, **kwargs) -> LROPoller[DeletedKey]: ...
99
```
100
101
[Key Management](./key-management.md)
102
103
### Cryptographic Operations
104
105
Comprehensive cryptographic operations using Azure Key Vault keys including encryption, decryption, digital signing, signature verification, and key wrapping. Supports multiple algorithms and integrates with Python's cryptography library.
106
107
```python { .api }
108
def encrypt(algorithm: EncryptionAlgorithm, plaintext: bytes, **kwargs) -> EncryptResult: ...
109
def decrypt(algorithm: EncryptionAlgorithm, ciphertext: bytes, **kwargs) -> DecryptResult: ...
110
def sign(algorithm: SignatureAlgorithm, digest: bytes, **kwargs) -> SignResult: ...
111
def verify(algorithm: SignatureAlgorithm, digest: bytes, signature: bytes, **kwargs) -> VerifyResult: ...
112
def wrap_key(algorithm: KeyWrapAlgorithm, key: bytes, **kwargs) -> WrapResult: ...
113
def unwrap_key(algorithm: KeyWrapAlgorithm, encrypted_key: bytes, **kwargs) -> UnwrapResult: ...
114
```
115
116
[Cryptographic Operations](./crypto-operations.md)
117
118
### Key Backup and Recovery
119
120
Backup and restore functionality for keys, enabling key migration and disaster recovery scenarios. Also includes soft-delete and recovery operations for accidental deletion protection.
121
122
```python { .api }
123
def backup_key(name: str, **kwargs) -> bytes: ...
124
def restore_key_backup(backup: bytes, **kwargs) -> KeyVaultKey: ...
125
def list_deleted_keys(**kwargs) -> ItemPaged[DeletedKey]: ...
126
def get_deleted_key(name: str, **kwargs) -> DeletedKey: ...
127
def begin_recover_deleted_key(name: str, **kwargs) -> LROPoller[KeyVaultKey]: ...
128
def purge_deleted_key(name: str, **kwargs) -> None: ...
129
```
130
131
[Key Backup and Recovery](./backup-recovery.md)
132
133
### Key Import and Export
134
135
Import keys from external sources and export keys with secure release policies. Supports JSON Web Key (JWK) format and secure key release for data protection scenarios.
136
137
```python { .api }
138
def import_key(name: str, key: JsonWebKey, **kwargs) -> KeyVaultKey: ...
139
def release_key(name: str, target_attestation_token: str, **kwargs) -> ReleaseKeyResult: ...
140
```
141
142
[Key Import and Export](./import-export.md)
143
144
### Key Rotation and Policies
145
146
Automated key rotation management with configurable policies, lifetime actions, and rotation triggers. Enables compliance with security policies requiring regular key rotation.
147
148
```python { .api }
149
def get_key_rotation_policy(key_name: str, **kwargs) -> KeyRotationPolicy: ...
150
def update_key_rotation_policy(key_name: str, policy: KeyRotationPolicy, **kwargs) -> KeyRotationPolicy: ...
151
def rotate_key(name: str, **kwargs) -> KeyVaultKey: ...
152
```
153
154
[Key Rotation and Policies](./rotation-policies.md)
155
156
### Asynchronous Operations
157
158
Complete async/await support for all key management and cryptographic operations, enabling efficient non-blocking I/O in async applications.
159
160
```python { .api }
161
async def create_key(name: str, key_type: KeyType, **kwargs) -> KeyVaultKey: ...
162
async def encrypt(algorithm: EncryptionAlgorithm, plaintext: bytes, **kwargs) -> EncryptResult: ...
163
async def decrypt(algorithm: EncryptionAlgorithm, ciphertext: bytes, **kwargs) -> DecryptResult: ...
164
```
165
166
[Asynchronous Operations](./async-operations.md)
167
168
## Common Types
169
170
```python { .api }
171
class KeyVaultKey:
172
"""A key's attributes and cryptographic material."""
173
id: str
174
name: str
175
properties: KeyProperties
176
key: JsonWebKey
177
key_type: KeyType
178
key_operations: List[KeyOperation]
179
180
class KeyProperties:
181
"""A key's ID and attributes without cryptographic material."""
182
id: str
183
name: str
184
version: str
185
enabled: bool
186
not_before: datetime
187
expires_on: datetime
188
created_on: datetime
189
updated_on: datetime
190
vault_url: str
191
recoverable_days: int
192
recovery_level: str
193
tags: Dict[str, str]
194
managed: bool
195
exportable: bool
196
197
class JsonWebKey:
198
"""JSON Web Key representation as defined in RFC 7517."""
199
kid: str
200
kty: KeyType
201
key_ops: List[KeyOperation]
202
# RSA parameters
203
n: bytes # RSA modulus
204
e: bytes # RSA public exponent
205
d: bytes # RSA private exponent
206
dp: bytes # RSA private key parameter
207
dq: bytes # RSA private key parameter
208
qi: bytes # RSA private key parameter
209
p: bytes # RSA secret prime
210
q: bytes # RSA secret prime
211
# EC parameters
212
crv: KeyCurveName # Elliptic curve name
213
x: bytes # X component of EC public key
214
y: bytes # Y component of EC public key
215
# Symmetric key parameters
216
k: bytes # Symmetric key
217
# HSM token
218
t: bytes # HSM Token for Bring Your Own Key
219
220
class DeletedKey(KeyVaultKey):
221
"""A deleted key's properties and deletion information."""
222
deleted_on: datetime # When the key was deleted
223
recovery_id: str # Recovery identifier for deleted key
224
scheduled_purge_date: datetime # When key will be permanently deleted
225
226
class KeyVaultKeyIdentifier:
227
"""Information about a KeyVaultKey parsed from a key ID."""
228
source_id: str # The complete key identifier URL
229
vault_url: str # The Key Vault URL
230
name: str # The key name
231
version: str # The key version (optional)
232
233
class KeyReleasePolicy:
234
"""The policy rules under which a key can be exported."""
235
encoded_policy: bytes # The policy rules encoded based on content_type
236
content_type: str # Content type and version of the release policy
237
immutable: bool # Whether the policy is immutable
238
239
class KeyRotationLifetimeAction:
240
"""Action and trigger performed over a key's lifetime."""
241
action: KeyRotationPolicyAction # The action to execute
242
time_after_create: str # Time after creation as ISO 8601 duration
243
time_before_expiry: str # Time before expiry as ISO 8601 duration
244
245
class KeyRotationPolicy:
246
"""Key rotation policy configuration."""
247
id: str # Policy identifier
248
lifetime_actions: List[KeyRotationLifetimeAction] # Lifetime actions
249
expires_in: str # Expiration time as ISO 8601 duration
250
created_on: datetime # When policy was created
251
updated_on: datetime # When policy was last updated
252
253
class ReleaseKeyResult:
254
"""Result of a key release operation."""
255
value: str # The released key value
256
257
class KeyType(str, Enum):
258
"""Supported key types."""
259
ec = "EC"
260
ec_hsm = "EC-HSM"
261
rsa = "RSA"
262
rsa_hsm = "RSA-HSM"
263
oct = "oct"
264
oct_hsm = "oct-HSM"
265
266
class KeyCurveName(str, Enum):
267
"""Supported elliptic curves."""
268
p_256 = "P-256" # NIST P-256 elliptic curve
269
p_384 = "P-384" # NIST P-384 elliptic curve
270
p_521 = "P-521" # NIST P-521 elliptic curve
271
p_256_k = "P-256K" # SECG SECP256K1 elliptic curve
272
273
class KeyOperation(str, Enum):
274
"""Supported key operations."""
275
encrypt = "encrypt"
276
decrypt = "decrypt"
277
sign = "sign"
278
verify = "verify"
279
wrap_key = "wrapKey"
280
unwrap_key = "unwrapKey"
281
import_key = "import"
282
export = "export"
283
284
class KeyExportEncryptionAlgorithm(str, Enum):
285
"""Supported algorithms for protecting exported key material."""
286
ckm_rsa_aes_key_wrap = "CKM_RSA_AES_KEY_WRAP"
287
rsa_aes_key_wrap_256 = "RSA_AES_KEY_WRAP_256"
288
rsa_aes_key_wrap_384 = "RSA_AES_KEY_WRAP_384"
289
290
class KeyRotationPolicyAction(str, Enum):
291
"""The action that will be executed in a key rotation policy."""
292
rotate = "Rotate" # Rotate the key based on the key policy
293
notify = "Notify" # Trigger Event Grid events
294
295
class ApiVersion(str, Enum):
296
"""Key Vault API versions supported by the client."""
297
V7_6 = "7.6" # Latest version (default)
298
V7_5 = "7.5"
299
V7_4 = "7.4"
300
V7_3 = "7.3"
301
V7_2 = "7.2"
302
V7_1 = "7.1"
303
V7_0 = "7.0"
304
V2016_10_01 = "2016-10-01"
305
306
# Package version constant
307
__version__: str # Current package version (e.g., "4.11.0")
308
```