azure.keyvault.keys.crypto.aio package

class azure.keyvault.keys.crypto.aio.CryptographyClient(key: KeyVaultKey | str, credential: AsyncTokenCredential, **kwargs: Any)[source]

Performs cryptographic operations using Azure Key Vault keys.

This client will perform operations locally when it’s intialized with the necessary key material or is able to get that material from Key Vault. When the required key material is unavailable, cryptographic operations are performed by the Key Vault service.

Parameters:
Keyword Arguments:
  • api_version (ApiVersion or str) – Version of the service API to use. Defaults to the most recent.

  • verify_challenge_resource (bool) – Whether to verify the authentication challenge resource matches the Key Vault or Managed HSM domain. Defaults to True.

Create a CryptographyClient
# create a CryptographyClient using a KeyVaultKey instance
key = await key_client.get_key(key_name)
crypto_client = CryptographyClient(key, credential)

# or a key's id, which must include a version
key_id = "https://<your vault>.vault.azure.net/keys/<key name>/fe4fdcab688c479a9aa80f01ffeac26"
crypto_client = CryptographyClient(key_id, credential)

# the client and credential should be closed when no longer needed
# (both are also async context managers)
await crypto_client.close()
await credential.close()
async close() None

Close sockets opened by the client.

Calling this method is unnecessary when using the client as a context manager.

async decrypt(algorithm: EncryptionAlgorithm, ciphertext: bytes, **kwargs: Any) DecryptResult[source]

Decrypt a single block of encrypted data using the client’s key.

Requires the keys/decrypt permission. This method decrypts only a single block of data, whose size depends on the key and encryption algorithm.

Parameters:
Keyword Arguments:
  • iv (bytes or None) – The initialization vector used during encryption. Required for AES decryption.

  • authentication_tag (bytes or None) – The authentication tag generated during encryption. Required for only AES-GCM decryption.

  • additional_authenticated_data (bytes or None) – Optional data that is authenticated but not encrypted. For use with AES-GCM decryption.

Returns:

The result of the decryption operation.

Return type:

DecryptResult

Raises:

ValueError – If parameters that are incompatible with the specified algorithm are provided.

Decrypt bytes
from azure.keyvault.keys.crypto import EncryptionAlgorithm

result = await client.decrypt(EncryptionAlgorithm.rsa_oaep, ciphertext)
print(result.plaintext)
async encrypt(algorithm: EncryptionAlgorithm, plaintext: bytes, **kwargs: Any) EncryptResult[source]

Encrypt bytes using the client’s key.

Requires the keys/encrypt permission. This method encrypts only a single block of data, whose size depends on the key and encryption algorithm.

Parameters:
Keyword Arguments:
  • iv (bytes or None) – Initialization vector. Required for only AES-CBC(PAD) encryption. If you pass your own IV, make sure you use a cryptographically random, non-repeating IV. If omitted, an attempt will be made to generate an IV via os.urandom for local cryptography; for remote cryptography, Key Vault will generate an IV.

  • additional_authenticated_data (bytes or None) – Optional data that is authenticated but not encrypted. For use with AES-GCM encryption.

Returns:

The result of the encryption operation.

Return type:

EncryptResult

Raises:

ValueError – if parameters that are incompatible with the specified algorithm are provided, or if generating an IV fails on the current platform.

Encrypt bytes
from azure.keyvault.keys.crypto import EncryptionAlgorithm

# the result holds the ciphertext and identifies the encryption key and algorithm used
result = await client.encrypt(EncryptionAlgorithm.rsa_oaep, b"plaintext")
print(result.key_id)
print(result.algorithm)
ciphertext = result.ciphertext
classmethod from_jwk(jwk: JsonWebKey | Dict[str, Any]) CryptographyClient[source]

Creates a client that can only perform cryptographic operations locally.

Parameters:

jwk (JsonWebKey or Dict[str, Any]) – the key’s cryptographic material, as a JsonWebKey or dictionary.

Returns:

A client that can only perform local cryptographic operations.

Return type:

CryptographyClient

async send_request(request: HttpRequest, *, stream: bool = False, **kwargs: Any) Awaitable[AsyncHttpResponse]

Runs a network request using the client’s existing pipeline.

The request URL can be relative to the vault URL. The service API version used for the request is the same as the client’s unless otherwise specified. This method does not raise if the response is an error; to raise an exception, call raise_for_status() on the returned response object. For more information about how to send custom requests with this method, see https://aka.ms/azsdk/dpcodegen/python/send_request.

Parameters:

request (HttpRequest) – The network request you want to make.

Keyword Arguments:

stream (bool) – Whether the response payload will be streamed. Defaults to False.

Returns:

The response of your network call. Does not do error handling on your response.

Return type:

AsyncHttpResponse

async sign(algorithm: SignatureAlgorithm, digest: bytes, **kwargs: Any) SignResult[source]

Create a signature from a digest using the client’s key.

Requires the keys/sign permission.

Parameters:
Returns:

The result of the signing operation.

Return type:

SignResult

Sign bytes
import hashlib

from azure.keyvault.keys.crypto import SignatureAlgorithm

digest = hashlib.sha256(b"plaintext").digest()

# sign returns the signature and the metadata required to verify it
result = await client.sign(SignatureAlgorithm.rs256, digest)
print(result.key_id)
print(result.algorithm)
signature = result.signature
async unwrap_key(algorithm: KeyWrapAlgorithm, encrypted_key: bytes, **kwargs: Any) UnwrapResult[source]

Unwrap a key previously wrapped with the client’s key.

Requires the keys/unwrapKey permission.

Parameters:
Returns:

The result of the unwrapping operation.

Return type:

UnwrapResult

Unwrap a key
from azure.keyvault.keys.crypto import KeyWrapAlgorithm

result = await client.unwrap_key(KeyWrapAlgorithm.rsa_oaep, encrypted_key)
async verify(algorithm: SignatureAlgorithm, digest: bytes, signature: bytes, **kwargs: Any) VerifyResult[source]

Verify a signature using the client’s key.

Requires the keys/verify permission.

Parameters:
  • algorithm (SignatureAlgorithm) – verification algorithm

  • digest (bytes) – Pre-hashed digest corresponding to signature. The hash algorithm used must be compatible with algorithm.

  • signature (bytes) – signature to verify

Returns:

The result of the verifying operation.

Return type:

VerifyResult

Verify a signature
from azure.keyvault.keys.crypto import SignatureAlgorithm

verified = await client.verify(SignatureAlgorithm.rs256, digest, signature)
assert verified.is_valid
async wrap_key(algorithm: KeyWrapAlgorithm, key: bytes, **kwargs: Any) WrapResult[source]

Wrap a key with the client’s key.

Requires the keys/wrapKey permission.

Parameters:
Returns:

The result of the wrapping operation.

Return type:

WrapResult

Wrap a key
from azure.keyvault.keys.crypto import KeyWrapAlgorithm

# wrap returns a tuple with the wrapped bytes and the metadata required to unwrap the key
result = await client.wrap_key(KeyWrapAlgorithm.rsa_oaep, key_bytes)
print(result.key_id)
print(result.algorithm)
encrypted_key = result.encrypted_key
property key_id: str | None

The full identifier of the client’s key.

This property may be None when a client is constructed with from_jwk().

Returns:

The full identifier of the client’s key.

Return type:

str or None

property vault_url: str | None

The base vault URL of the client’s key.

This property may be None when a client is constructed with from_jwk().

Returns:

The base vault URL of the client’s key.

Return type:

str or None