or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-operations.mdbackup-recovery.mdcrypto-operations.mdimport-export.mdindex.mdkey-management.mdrotation-policies.md

crypto-operations.mddocs/

0

# Cryptographic Operations

1

2

Comprehensive cryptographic operations using Azure Key Vault keys including encryption, decryption, digital signing, signature verification, and key wrapping. The CryptographyClient provides a high-level interface for performing cryptographic operations with keys stored in Azure Key Vault, integrating seamlessly with Python's cryptography library.

3

4

## Capabilities

5

6

### Encryption and Decryption

7

8

Encrypt and decrypt data using various symmetric and asymmetric algorithms.

9

10

```python { .api }

11

def encrypt(

12

algorithm: EncryptionAlgorithm,

13

plaintext: bytes,

14

*,

15

iv: bytes = None,

16

additional_authenticated_data: bytes = None,

17

**kwargs

18

) -> EncryptResult:

19

"""

20

Encrypt data using the key.

21

22

Parameters:

23

- algorithm: Encryption algorithm to use

24

- plaintext: Data to encrypt

25

- iv: Initialization vector (required for some algorithms)

26

- additional_authenticated_data: Additional data for authenticated encryption

27

28

Returns:

29

EncryptResult: Encryption result with ciphertext and metadata

30

"""

31

32

def decrypt(

33

algorithm: EncryptionAlgorithm,

34

ciphertext: bytes,

35

*,

36

iv: bytes = None,

37

authentication_tag: bytes = None,

38

additional_authenticated_data: bytes = None,

39

**kwargs

40

) -> DecryptResult:

41

"""

42

Decrypt data using the key.

43

44

Parameters:

45

- algorithm: Encryption algorithm used for encryption

46

- ciphertext: Data to decrypt

47

- iv: Initialization vector (if used during encryption)

48

- authentication_tag: Authentication tag (for authenticated encryption)

49

- additional_authenticated_data: Additional data (if used during encryption)

50

51

Returns:

52

DecryptResult: Decryption result with plaintext

53

"""

54

```

55

56

#### Usage Examples

57

58

```python

59

from azure.keyvault.keys.crypto import CryptographyClient, EncryptionAlgorithm

60

from azure.identity import DefaultAzureCredential

61

62

# Create crypto client

63

key_id = "https://vault.vault.azure.net/keys/my-key/version"

64

crypto_client = CryptographyClient(key_id, DefaultAzureCredential())

65

66

# RSA encryption

67

plaintext = b"Hello, World!"

68

encrypt_result = crypto_client.encrypt(EncryptionAlgorithm.rsa_oaep_256, plaintext)

69

decrypt_result = crypto_client.decrypt(EncryptionAlgorithm.rsa_oaep_256, encrypt_result.ciphertext)

70

71

# AES-GCM encryption

72

import os

73

plaintext = b"Sensitive data"

74

encrypt_result = crypto_client.encrypt(

75

EncryptionAlgorithm.a256_gcm,

76

plaintext,

77

iv=os.urandom(12) # 96-bit IV for GCM

78

)

79

decrypt_result = crypto_client.decrypt(

80

EncryptionAlgorithm.a256_gcm,

81

encrypt_result.ciphertext,

82

iv=encrypt_result.iv,

83

authentication_tag=encrypt_result.tag

84

)

85

```

86

87

### Digital Signatures

88

89

Create and verify digital signatures using asymmetric keys.

90

91

```python { .api }

92

def sign(algorithm: SignatureAlgorithm, digest: bytes, **kwargs) -> SignResult:

93

"""

94

Sign a digest using the key.

95

96

Parameters:

97

- algorithm: Signature algorithm to use

98

- digest: Pre-computed hash digest to sign

99

100

Returns:

101

SignResult: Signature result

102

"""

103

104

def verify(

105

algorithm: SignatureAlgorithm,

106

digest: bytes,

107

signature: bytes,

108

**kwargs

109

) -> VerifyResult:

110

"""

111

Verify a signature using the key.

112

113

Parameters:

114

- algorithm: Signature algorithm used for signing

115

- digest: Original hash digest that was signed

116

- signature: Signature to verify

117

118

Returns:

119

VerifyResult: Verification result indicating validity

120

"""

121

```

122

123

#### Usage Examples

124

125

```python

126

import hashlib

127

from azure.keyvault.keys.crypto import SignatureAlgorithm

128

129

# Create a hash digest

130

data = b"Important document content"

131

digest = hashlib.sha256(data).digest()

132

133

# Sign the digest

134

sign_result = crypto_client.sign(SignatureAlgorithm.rs256, digest)

135

print(f"Signature: {sign_result.signature.hex()}")

136

137

# Verify the signature

138

verify_result = crypto_client.verify(SignatureAlgorithm.rs256, digest, sign_result.signature)

139

print(f"Signature valid: {verify_result.is_valid}")

140

141

# ECDSA signing

142

ec_crypto_client = CryptographyClient("https://vault.vault.azure.net/keys/my-ec-key/version", credential)

143

sign_result = ec_crypto_client.sign(SignatureAlgorithm.es256, digest)

144

verify_result = ec_crypto_client.verify(SignatureAlgorithm.es256, digest, sign_result.signature)

145

```

146

147

### Key Wrapping and Unwrapping

148

149

Wrap (encrypt) and unwrap (decrypt) symmetric keys using key encryption keys.

150

151

```python { .api }

152

def wrap_key(algorithm: KeyWrapAlgorithm, key: bytes, **kwargs) -> WrapResult:

153

"""

154

Wrap (encrypt) a key using a key encryption key.

155

156

Parameters:

157

- algorithm: Key wrap algorithm to use

158

- key: Key material to wrap

159

160

Returns:

161

WrapResult: Wrapped key result

162

"""

163

164

def unwrap_key(algorithm: KeyWrapAlgorithm, encrypted_key: bytes, **kwargs) -> UnwrapResult:

165

"""

166

Unwrap (decrypt) a key using a key encryption key.

167

168

Parameters:

169

- algorithm: Key wrap algorithm used for wrapping

170

- encrypted_key: Wrapped key material to unwrap

171

172

Returns:

173

UnwrapResult: Unwrapped key result

174

"""

175

```

176

177

#### Usage Examples

178

179

```python

180

from azure.keyvault.keys.crypto import KeyWrapAlgorithm

181

import os

182

183

# Generate a data encryption key

184

data_key = os.urandom(32) # 256-bit key

185

186

# Wrap the key

187

wrap_result = crypto_client.wrap_key(KeyWrapAlgorithm.rsa_oaep_256, data_key)

188

print(f"Wrapped key: {wrap_result.encrypted_key.hex()}")

189

190

# Unwrap the key

191

unwrap_result = crypto_client.unwrap_key(KeyWrapAlgorithm.rsa_oaep_256, wrap_result.encrypted_key)

192

print(f"Keys match: {unwrap_result.key == data_key}")

193

194

# AES key wrapping

195

aes_kek_client = CryptographyClient("https://vault.vault.azure.net/keys/my-aes-key/version", credential)

196

wrap_result = aes_kek_client.wrap_key(KeyWrapAlgorithm.aes_256, data_key)

197

unwrap_result = aes_kek_client.unwrap_key(KeyWrapAlgorithm.aes_256, wrap_result.encrypted_key)

198

```

199

200

### Cryptography Library Integration

201

202

Create RSA key objects compatible with Python's cryptography library.

203

204

```python { .api }

205

def create_rsa_private_key(**kwargs) -> KeyVaultRSAPrivateKey:

206

"""

207

Create an RSA private key object backed by Key Vault.

208

209

Returns:

210

KeyVaultRSAPrivateKey: RSA private key implementation using Key Vault

211

"""

212

213

def create_rsa_public_key(**kwargs) -> KeyVaultRSAPublicKey:

214

"""

215

Create an RSA public key object backed by Key Vault.

216

217

Returns:

218

KeyVaultRSAPublicKey: RSA public key implementation using Key Vault

219

"""

220

```

221

222

#### Usage Examples

223

224

```python

225

from cryptography.hazmat.primitives import hashes, serialization

226

from cryptography.hazmat.primitives.asymmetric import padding

227

228

# Create Key Vault-backed RSA key objects

229

private_key = crypto_client.create_rsa_private_key()

230

public_key = private_key.public_key()

231

232

# Use with cryptography library patterns

233

message = b"Hello from cryptography library!"

234

235

# Encrypt using public key

236

ciphertext = public_key.encrypt(

237

message,

238

padding.OAEP(

239

mgf=padding.MGF1(algorithm=hashes.SHA256()),

240

algorithm=hashes.SHA256(),

241

label=None

242

)

243

)

244

245

# Decrypt using private key

246

plaintext = private_key.decrypt(

247

ciphertext,

248

padding.OAEP(

249

mgf=padding.MGF1(algorithm=hashes.SHA256()),

250

algorithm=hashes.SHA256(),

251

label=None

252

)

253

)

254

255

# Serialize public key

256

public_pem = public_key.public_bytes(

257

encoding=serialization.Encoding.PEM,

258

format=serialization.PublicFormat.SubjectPublicKeyInfo

259

)

260

```

261

262

### Client Creation

263

264

Various methods for creating CryptographyClient instances.

265

266

```python { .api }

267

def __init__(

268

key: Union[KeyVaultKey, str],

269

credential: TokenCredential,

270

**kwargs

271

):

272

"""

273

Create a CryptographyClient.

274

275

Parameters:

276

- key: KeyVaultKey object or key identifier URL

277

- credential: Azure credential for authentication

278

"""

279

280

@classmethod

281

def from_jwk(cls, jwk: Union[JsonWebKey, Dict[str, Any]], **kwargs) -> "CryptographyClient":

282

"""

283

Create a CryptographyClient from a JSON Web Key for local cryptographic operations.

284

285

Parameters:

286

- jwk: JSON Web Key containing cryptographic material

287

288

Returns:

289

CryptographyClient: Client for local cryptographic operations

290

"""

291

```

292

293

#### Usage Examples

294

295

```python

296

from azure.keyvault.keys import KeyClient

297

from azure.keyvault.keys.crypto import CryptographyClient

298

299

# From key ID

300

crypto_client = CryptographyClient("https://vault.vault.azure.net/keys/my-key/version", credential)

301

302

# From KeyVaultKey object

303

key_client = KeyClient("https://vault.vault.azure.net/", credential)

304

key = key_client.get_key("my-key")

305

crypto_client = CryptographyClient(key, credential)

306

307

# From JWK for local operations

308

jwk = {

309

"kty": "RSA",

310

"n": "...", # RSA modulus

311

"e": "AQAB", # RSA public exponent

312

# ... other parameters

313

}

314

local_crypto_client = CryptographyClient.from_jwk(jwk)

315

```

316

317

## Types

318

319

```python { .api }

320

class CryptographyClient:

321

"""Client for performing cryptographic operations with Azure Key Vault keys."""

322

key_id: str

323

vault_url: str

324

325

class EncryptResult:

326

"""Result of an encrypt operation."""

327

key_id: str

328

algorithm: EncryptionAlgorithm

329

ciphertext: bytes

330

iv: bytes

331

tag: bytes

332

aad: bytes

333

334

class DecryptResult:

335

"""Result of a decrypt operation."""

336

key_id: str

337

algorithm: EncryptionAlgorithm

338

plaintext: bytes

339

340

class SignResult:

341

"""Result of a sign operation."""

342

key_id: str

343

algorithm: SignatureAlgorithm

344

signature: bytes

345

346

class VerifyResult:

347

"""Result of a verify operation."""

348

key_id: str

349

algorithm: SignatureAlgorithm

350

is_valid: bool

351

352

class WrapResult:

353

"""Result of a wrap key operation."""

354

key_id: str

355

algorithm: KeyWrapAlgorithm

356

encrypted_key: bytes

357

358

class UnwrapResult:

359

"""Result of an unwrap key operation."""

360

key_id: str

361

algorithm: KeyWrapAlgorithm

362

key: bytes

363

364

class KeyVaultRSAPrivateKey:

365

"""RSA private key implementation backed by Key Vault."""

366

key_size: int

367

def decrypt(ciphertext: bytes, padding) -> bytes: ...

368

def sign(data: bytes, padding, algorithm) -> bytes: ...

369

def public_key() -> KeyVaultRSAPublicKey: ...

370

def private_numbers() -> RSAPrivateNumbers: ...

371

def private_bytes(encoding, format, encryption_algorithm) -> bytes: ...

372

373

class KeyVaultRSAPublicKey:

374

"""RSA public key implementation backed by Key Vault."""

375

key_size: int

376

def encrypt(plaintext: bytes, padding) -> bytes: ...

377

def verify(signature: bytes, data: bytes, padding, algorithm) -> None: ...

378

def public_numbers() -> RSAPublicNumbers: ...

379

def public_bytes(encoding, format) -> bytes: ...

380

381

class EncryptionAlgorithm(str, Enum):

382

"""Encryption algorithms."""

383

# RSA algorithms

384

rsa_oaep = "RSA-OAEP"

385

rsa_oaep_256 = "RSA-OAEP-256"

386

rsa1_5 = "RSA1_5"

387

# AES GCM algorithms

388

a128_gcm = "A128GCM"

389

a192_gcm = "A192GCM"

390

a256_gcm = "A256GCM"

391

# AES CBC algorithms

392

a128_cbc = "A128CBC"

393

a192_cbc = "A192CBC"

394

a256_cbc = "A256CBC"

395

# AES CBC with PKCS7 padding

396

a128_cbcpad = "A128CBCPAD"

397

a192_cbcpad = "A192CBCPAD"

398

a256_cbcpad = "A256CBCPAD"

399

400

class KeyWrapAlgorithm(str, Enum):

401

"""Key wrapping algorithms."""

402

# AES key wrap algorithms

403

aes_128 = "A128KW"

404

aes_192 = "A192KW"

405

aes_256 = "A256KW"

406

# RSA key wrap algorithms

407

rsa_oaep = "RSA-OAEP"

408

rsa_oaep_256 = "RSA-OAEP-256"

409

rsa1_5 = "RSA1_5"

410

# PKCS#11 mechanisms

411

ckm_aes_key_wrap = "CKM_AES_KEY_WRAP"

412

ckm_aes_key_wrap_pad = "CKM_AES_KEY_WRAP_PAD"

413

414

class SignatureAlgorithm(str, Enum):

415

"""Signature algorithms."""

416

# RSA PSS algorithms

417

ps256 = "PS256" # RSASSA-PSS using SHA-256

418

ps384 = "PS384" # RSASSA-PSS using SHA-384

419

ps512 = "PS512" # RSASSA-PSS using SHA-512

420

# RSA PKCS#1 v1.5 algorithms

421

rs256 = "RS256" # RSASSA-PKCS1-v1_5 using SHA-256

422

rs384 = "RS384" # RSASSA-PKCS1-v1_5 using SHA-384

423

rs512 = "RS512" # RSASSA-PKCS1-v1_5 using SHA-512

424

# ECDSA algorithms

425

es256 = "ES256" # ECDSA using P-256 and SHA-256

426

es384 = "ES384" # ECDSA using P-384 and SHA-384

427

es512 = "ES512" # ECDSA using P-521 and SHA-512

428

es256_k = "ES256K" # ECDSA using P-256K and SHA-256

429

# HMAC algorithms

430

hs256 = "HS256" # HMAC using SHA-256

431

hs384 = "HS384" # HMAC using SHA-384

432

hs512 = "HS512" # HMAC using SHA-512

433

```