azure.keyvault.keys.aio package

class azure.keyvault.keys.aio.KeyClient(vault_url: str, credential: AsyncTokenCredential, **kwargs: Any)[source]

A high-level asynchronous interface for managing a vault’s keys.

Parameters:
  • vault_url (str) – URL of the vault the client will access. This is also called the vault’s “DNS Name”. You should validate that this URL references a valid Key Vault or Managed HSM resource. See https://aka.ms/azsdk/blog/vault-uri for details.

  • credential (AsyncTokenCredential) – An object which can provide an access token for the vault, such as a credential from azure.identity.aio

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.

Example

Create a new KeyClient
from azure.identity.aio import DefaultAzureCredential
from azure.keyvault.keys.aio import KeyClient

# Create a KeyClient using default Azure credentials
credential = DefaultAzureCredential()
key_client = KeyClient(vault_url, credential)

# the client and credential should be closed when no longer needed
# (both are also async context managers)
await key_client.close()
await credential.close()
async backup_key(name: str, **kwargs: Any) bytes[source]

Back up a key in a protected form useable only by Azure Key Vault.

Requires key/backup permission. This is intended to allow copying a key from one vault to another. Both vaults must be owned by the same Azure subscription. Also, backup / restore cannot be performed across geopolitical boundaries. For example, a backup from a vault in a USA region cannot be restored to a vault in an EU region.

Parameters:

name (str) – The name of the key to back up

Returns:

The key backup result, in a protected bytes format that can only be used by Azure Key Vault.

Return type:

bytes

Raises:

ResourceNotFoundError or HttpResponseError – the former if the key doesn’t exist; the latter for other errors

Example

Get a key backup
# backup key
key_backup = await key_client.backup_key(key_name)

# returns the raw bytes of the backup
print(key_backup)
async close() None

Close sockets opened by the client.

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

async create_ec_key(name: str, **kwargs: Any) KeyVaultKey[source]

Create a new elliptic curve key or, if name is already in use, create a new version of the key.

Requires the keys/create permission.

Parameters:

name (str) – The name for the new key.

Keyword Arguments:
  • curve (KeyCurveName or str or None) – Elliptic curve name. Defaults to the NIST P-256 elliptic curve.

  • key_operations (list[KeyOperation or str] or None) – Allowed key operations

  • hardware_protected (bool or None) – Whether the key should be created in a hardware security module. Defaults to False.

  • enabled (bool or None) – Whether the key is enabled for use.

  • tags (dict[str, str] or None) – Application specific metadata in the form of key-value pairs.

  • not_before (datetime or None) – Not before date of the key in UTC

  • expires_on (datetime or None) – Expiry date of the key in UTC

  • exportable (bool or None) – Whether the private key can be exported.

  • release_policy (KeyReleasePolicy or None) – The policy rules under which the key can be exported.

Returns:

The created key

Return type:

KeyVaultKey

Raises:

HttpResponseError

Example

Create an elliptic curve key
# create an elliptic curve (ec) key
key_curve = "P-256"
ec_key = await key_client.create_ec_key(key_name, curve=key_curve)

print(ec_key.id)
print(ec_key.name)
print(ec_key.key_type)
print(ec_key.key.crv)
async create_key(name: str, key_type: str | KeyType, **kwargs: Any) KeyVaultKey[source]

Create a key or, if name is already in use, create a new version of the key.

Requires keys/create permission.

Parameters:
  • name (str) – The name of the new key.

  • key_type (KeyType or str) – The type of key to create

Keyword Arguments:
  • size (int or None) – Key size in bits. Applies only to RSA and symmetric keys. Consider using create_rsa_key() or create_oct_key() instead.

  • curve (KeyCurveName or str or None) – Elliptic curve name. Applies only to elliptic curve keys. Defaults to the NIST P-256 elliptic curve. To create an elliptic curve key, consider using create_ec_key() instead.

  • public_exponent (int or None) – The RSA public exponent to use. Applies only to RSA keys created in a Managed HSM.

  • key_operations (list[KeyOperation or str] or None) – Allowed key operations

  • enabled (bool or None) – Whether the key is enabled for use.

  • tags (dict[str, str] or None) – Application specific metadata in the form of key-value pairs.

  • not_before (datetime or None) – Not before date of the key in UTC

  • expires_on (datetime or None) – Expiry date of the key in UTC

  • exportable (bool or None) – Whether the private key can be exported.

  • release_policy (KeyReleasePolicy or None) – The policy rules under which the key can be exported.

Returns:

The created key

Return type:

KeyVaultKey

Raises:

HttpResponseError

Example

Create a key
from dateutil import parser as date_parse

key_size = 2048
key_ops = ["encrypt", "decrypt", "sign", "verify", "wrapKey", "unwrapKey"]
expires_on = date_parse.parse("2050-02-02T08:00:00.000Z")

# create a key with optional arguments
key = await key_client.create_key(
    key_name, KeyType.rsa, size=key_size, key_operations=key_ops, expires_on=expires_on
)

print(key.id)
print(key.name)
print(key.key_type)
print(key.properties.enabled)
print(key.properties.expires_on)
async create_oct_key(name: str, **kwargs: Any) KeyVaultKey[source]

Create a new octet sequence (symmetric) key or, if name is in use, create a new version of the key.

Requires the keys/create permission.

Parameters:

name (str) – The name for the new key.

Keyword Arguments:
  • size (int or None) – Key size in bits, for example 128, 192, or 256.

  • key_operations (list[KeyOperation or str] or None) – Allowed key operations.

  • hardware_protected (bool or None) – Whether the key should be created in a hardware security module. Defaults to False.

  • enabled (bool or None) – Whether the key is enabled for use.

  • tags (dict[str, str] or None) – Application specific metadata in the form of key-value pairs.

  • not_before (datetime or None) – Not before date of the key in UTC

  • expires_on (datetime or None) – Expiry date of the key in UTC

  • exportable (bool or None) – Whether the key can be exported.

  • release_policy (KeyReleasePolicy or None) – The policy rules under which the key can be exported.

Returns:

The created key

Return type:

KeyVaultKey

Raises:

HttpResponseError

Example

Create an octet sequence (symmetric) key
key = await key_client.create_oct_key(key_name, size=256, hardware_protected=True)

print(key.id)
print(key.name)
print(key.key_type)
async create_rsa_key(name: str, **kwargs: Any) KeyVaultKey[source]

Create a new RSA key or, if name is already in use, create a new version of the key

Requires the keys/create permission.

Parameters:

name (str) – The name for the new key.

Keyword Arguments:
  • size (int or None) – Key size in bits, for example 2048, 3072, or 4096.

  • public_exponent (int or None) – The RSA public exponent to use. Applies only to RSA keys created in a Managed HSM.

  • hardware_protected (bool or None) – Whether the key should be created in a hardware security module. Defaults to False.

  • key_operations (list[KeyOperation or str] or None) – Allowed key operations

  • enabled (bool or None) – Whether the key is enabled for use.

  • tags (dict[str, str] or None) – Application specific metadata in the form of key-value pairs.

  • not_before (datetime or None) – Not before date of the key in UTC

  • expires_on (datetime or None) – Expiry date of the key in UTC

  • exportable (bool or None) – Whether the private key can be exported.

  • release_policy (KeyReleasePolicy or None) – The policy rules under which the key can be exported.

Returns:

The created key

Return type:

KeyVaultKey

Raises:

HttpResponseError

Example

Create RSA key
# create an rsa key in a hardware security module
key = await key_client.create_rsa_key(key_name, hardware_protected=True, size=2048)

print(key.id)
print(key.name)
print(key.key_type)
async delete_key(name: str, **kwargs: Any) DeletedKey[source]

Delete all versions of a key and its cryptographic material.

Requires keys/delete permission. If the vault has soft-delete enabled, deletion may take several seconds to complete.

Parameters:

name (str) – The name of the key to delete

Returns:

The deleted key

Return type:

DeletedKey

Raises:

ResourceNotFoundError or HttpResponseError – the former if the key doesn’t exist; the latter for other errors

Example

Delete a key
# delete a key
deleted_key = await key_client.delete_key(key_name)

print(deleted_key.name)

# if the vault has soft-delete enabled, the key's
# scheduled purge date, deleted_date and recovery id are set
print(deleted_key.deleted_date)
print(deleted_key.scheduled_purge_date)
print(deleted_key.recovery_id)
get_cryptography_client(key_name: str, *, key_version: str | None = None, **kwargs) CryptographyClient[source]

Gets a CryptographyClient for the given key.

Parameters:

key_name (str) – The name of the key used to perform cryptographic operations.

Keyword Arguments:

key_version (str or None) – Optional version of the key used to perform cryptographic operations.

Returns:

A CryptographyClient using the same options, credentials, and HTTP client as this KeyClient.

Return type:

CryptographyClient

async get_deleted_key(name: str, **kwargs: Any) DeletedKey[source]

Get a deleted key. Possible only in a vault with soft-delete enabled.

Requires keys/get permission.

Parameters:

name (str) – The name of the key

Returns:

The deleted key

Return type:

DeletedKey

Raises:

ResourceNotFoundError or HttpResponseError – the former if the key doesn’t exist; the latter for other errors

Example

Get a deleted key
# get a deleted key (requires soft-delete enabled for the vault)
deleted_key = await key_client.get_deleted_key(key_name)
print(deleted_key.name)
async get_key(name: str, version: str | None = None, **kwargs: Any) KeyVaultKey[source]

Get a key’s attributes and, if it’s an asymmetric key, its public material.

Requires keys/get permission.

Parameters:
  • name (str) – The name of the key to get.

  • version (str or None) – (optional) A specific version of the key to get. If not specified, gets the latest version of the key.

Returns:

The fetched key.

Return type:

KeyVaultKey

Raises:

ResourceNotFoundError or HttpResponseError – the former if the key doesn’t exist; the latter for other errors

Example

Get a key
# get the latest version of a key
key = await key_client.get_key(key_name)

# alternatively, specify a version
key_version = key.properties.version
key = await key_client.get_key(key_name, key_version)

print(key.id)
print(key.name)
print(key.properties.version)
print(key.key_type)
print(key.properties.vault_url)
async get_key_rotation_policy(key_name: str, **kwargs: Any) KeyRotationPolicy[source]

Get the rotation policy of a Key Vault key.

Parameters:

key_name (str) – The name of the key.

Returns:

The key rotation policy.

Return type:

KeyRotationPolicy

Raises:

HttpResponseError

async get_random_bytes(count: int, **kwargs: Any) bytes[source]

Get the requested number of random bytes from a managed HSM.

Parameters:

count (int) – The requested number of random bytes.

Returns:

The random bytes.

Return type:

bytes

Raises:

ValueError or HttpResponseError – the former if less than one random byte is requested; the latter for other errors

Example

Get random bytes
# get eight random bytes from a managed HSM
random_bytes = await client.get_random_bytes(count=8)
async import_key(name: str, key: JsonWebKey, **kwargs: Any) KeyVaultKey[source]

Import a key created externally.

Requires keys/import permission. If name is already in use, the key will be imported as a new version.

Parameters:
  • name (str) – Name for the imported key

  • key (JsonWebKey) – The JSON web key to import

Keyword Arguments:
  • hardware_protected (bool or None) – Whether the key should be backed by a hardware security module

  • enabled (bool or None) – Whether the key is enabled for use.

  • tags (dict[str, str] or None) – Application specific metadata in the form of key-value pairs.

  • not_before (datetime or None) – Not before date of the key in UTC

  • expires_on (datetime or None) – Expiry date of the key in UTC

  • exportable (bool or None) – Whether the private key can be exported.

  • release_policy (KeyReleasePolicy or None) – The policy rules under which the key can be exported.

Returns:

The imported key

Return type:

KeyVaultKey

Raises:

HttpResponseError

list_deleted_keys(**kwargs: Any) AsyncItemPaged[DeletedKey][source]

List all deleted keys, including the public part of each. Possible only in a vault with soft-delete enabled.

Requires keys/list permission.

Returns:

An iterator of deleted keys

Return type:

AsyncItemPaged[DeletedKey]

Example

List all the deleted keys
# get an iterator of deleted keys (requires soft-delete enabled for the vault)
deleted_keys = key_client.list_deleted_keys()

async for key in deleted_keys:
    print(key.id)
    print(key.name)
    print(key.scheduled_purge_date)
    print(key.recovery_id)
    print(key.deleted_date)
list_properties_of_key_versions(name: str, **kwargs: Any) AsyncItemPaged[KeyProperties][source]

List the identifiers and properties of a key’s versions.

Requires keys/list permission.

Parameters:

name (str) – The name of the key

Returns:

An iterator of keys without their cryptographic material

Return type:

AsyncItemPaged[KeyProperties]

Example

List all versions of a key
# get an iterator of all versions of a key
key_versions = key_client.list_properties_of_key_versions("key-name")

async for key in key_versions:
    print(key.id)
    print(key.updated_on)
    print(key.properties.version)
    print(key.expires_on)
list_properties_of_keys(**kwargs: Any) AsyncItemPaged[KeyProperties][source]

List identifiers and properties of all keys in the vault.

Requires keys/list permission.

Returns:

An iterator of keys without their cryptographic material or version information

Return type:

AsyncItemPaged[KeyProperties]

Example

List all keys
# list keys
keys = key_client.list_properties_of_keys()

async for key in keys:
    print(key.id)
    print(key.created_on)
    print(key.name)
    print(key.updated_on)
    print(key.enabled)
async purge_deleted_key(name: str, **kwargs: Any) None[source]

Permanently deletes a deleted key. Only possible in a vault with soft-delete enabled.

Performs an irreversible deletion of the specified key, without possibility for recovery. The operation is not available if the recovery_level does not specify ‘Purgeable’. This method is only necessary for purging a key before its scheduled_purge_date.

Requires keys/purge permission.

Parameters:

name (str) – The name of the deleted key to purge

Returns:

None

Raises:

HttpResponseError

Example

# if the vault has soft-delete enabled, purge permanently deletes a deleted key
# (with soft-delete disabled, delete_key is permanent)
await key_client.purge_deleted_key("key-name")
async recover_deleted_key(name: str, **kwargs: Any) KeyVaultKey[source]

Recover a deleted key to its latest version. Possible only in a vault with soft-delete enabled.

Requires keys/recover permission. If the vault does not have soft-delete enabled, delete_key() is permanent, and this method will raise an error. Attempting to recover a non-deleted key will also raise an error.

Parameters:

name (str) – The name of the deleted key

Returns:

The recovered key

Return type:

KeyVaultKey

Raises:

HttpResponseError

Example

Recover a deleted key
# recover deleted key to its latest version (requires soft-delete enabled for the vault)
recovered_key = await key_client.recover_deleted_key(key_name)
print(recovered_key.id)
print(recovered_key.name)
async release_key(name: str, target_attestation_token: str, **kwargs: Any) ReleaseKeyResult[source]

Releases a key.

The release key operation is applicable to all key types. The target key must be marked exportable. This operation requires the keys/release permission.

Parameters:
  • name (str) – The name of the key to get.

  • target_attestation_token (str) – The attestation assertion for the target of the key release.

Keyword Arguments:
  • version (str or None) – A specific version of the key to release. If unspecified, the latest version is released.

  • algorithm (str or KeyExportEncryptionAlgorithm or None) – The encryption algorithm to use to protect the released key material.

  • nonce (str or None) – A client-provided nonce for freshness.

Returns:

The result of the key release.

Return type:

ReleaseKeyResult

Raises:

HttpResponseError

async restore_key_backup(backup: bytes, **kwargs: Any) KeyVaultKey[source]

Restore a key backup to the vault.

Requires keys/restore permission. This imports all versions of the key, with its name, attributes, and access control policies. If the key’s name is already in use, restoring it will fail. Also, the target vault must be owned by the same Microsoft Azure subscription as the source vault.

Parameters:

backup (bytes) – A key backup as returned by backup_key()

Returns:

The restored key

Return type:

KeyVaultKey

Raises:

ResourceExistsError or HttpResponseError – the former if the backed up key’s name is already in use; the latter for other errors

Example

Restore a key backup
# restores a backup
restored_key = await key_client.restore_key_backup(key_backup)
print(restored_key.id)
print(restored_key.name)
print(restored_key.properties.version)
async rotate_key(name: str, **kwargs: Any) KeyVaultKey[source]

Rotate the key based on the key policy by generating a new version of the key.

This operation requires the keys/rotate permission.

Parameters:

name (str) – The name of the key to rotate.

Returns:

The new version of the rotated key.

Return type:

KeyVaultKey

Raises:

HttpResponseError

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 update_key_properties(name: str, version: str | None = None, **kwargs: Any) KeyVaultKey[source]

Change a key’s properties (not its cryptographic material).

Requires keys/update permission.

Parameters:
  • name (str) – The name of key to update

  • version (str or None) – (optional) The version of the key to update. If unspecified, the latest version is updated.

Keyword Arguments:
  • key_operations (list[KeyOperation or str] or None) – Allowed key operations

  • enabled (bool or None) – Whether the key is enabled for use.

  • tags (dict[str, str] or None) – Application specific metadata in the form of key-value pairs.

  • not_before (datetime or None) – Not before date of the key in UTC

  • expires_on (datetime or None) – Expiry date of the key in UTC

  • release_policy (KeyReleasePolicy or None) – The policy rules under which the key can be exported.

Returns:

The updated key

Return type:

KeyVaultKey

Raises:

ResourceNotFoundError or HttpResponseError – the former if the key doesn’t exist; the latter for other errors

Example

Update a key’s attributes
# update attributes of an existing key
expires_on = date_parse.parse("2050-01-02T08:00:00.000Z")
tags = {"foo": "updated tag"}
updated_key = await key_client.update_key_properties(key.name, expires_on=expires_on, tags=tags)

print(updated_key.properties.version)
print(updated_key.properties.updated_on)
print(updated_key.properties.expires_on)
print(updated_key.properties.tags)
print(updated_key.key_type)
async update_key_rotation_policy(key_name: str, policy: KeyRotationPolicy, **kwargs: Any) KeyRotationPolicy[source]

Updates the rotation policy of a Key Vault key.

This operation requires the keys/update permission.

Parameters:
  • key_name (str) – The name of the key in the given vault.

  • policy (KeyRotationPolicy) – The new rotation policy for the key.

Keyword Arguments:
  • lifetime_actions (list[KeyRotationLifetimeAction]) – Actions that will be performed by Key Vault over the lifetime of a key. This will override the lifetime actions of the provided policy.

  • expires_in (str) – The expiry time of the policy that will be applied on new key versions, defined as an ISO 8601 duration. For example: 90 days is “P90D”, 3 months is “P3M”, and 48 hours is “PT48H”. See Wikipedia for more information on ISO 8601 durations. This will override the expiry time of the provided policy.

Returns:

The updated rotation policy.

Return type:

KeyRotationPolicy

Raises:

HttpResponseError

property vault_url: str