Security News
PyPI’s New Archival Feature Closes a Major Security Gap
PyPI now allows maintainers to archive projects, improving security and helping users make informed decisions about their dependencies.
Azure Key Vault helps solve the following problems:
Source code | Package (PyPI) | Package (Conda) | API reference documentation | Product documentation | Samples
Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691.
Python 3.8 or later is required to use this package. For more details, please refer to Azure SDK for Python version support policy.
Install azure-keyvault-keys and azure-identity with pip:
pip install azure-keyvault-keys azure-identity
azure-identity is used for Azure Active Directory authentication as demonstrated below.
In order to interact with the Azure Key Vault service, you will need an instance of a KeyClient, as well as a vault URL and a credential object. This document demonstrates using a DefaultAzureCredential, which is appropriate for most scenarios. We recommend using a managed identity for authentication in production environments.
See azure-identity documentation for more information about other methods of authentication and their corresponding credential types.
After configuring your environment for the DefaultAzureCredential to use a suitable method of
authentication, you can do the following to create a key client (replacing the value of VAULT_URL
with your vault's
URL):
from azure.identity import DefaultAzureCredential
from azure.keyvault.keys import KeyClient
VAULT_URL = os.environ["VAULT_URL"]
credential = DefaultAzureCredential()
client = KeyClient(vault_url=VAULT_URL, credential=credential)
NOTE: For an asynchronous client, import
azure.keyvault.keys.aio
'sKeyClient
instead.
Azure Key Vault can create and store RSA and elliptic curve keys. Both can optionally be protected by hardware security modules (HSMs). Azure Key Vault can also perform cryptographic operations with them. For more information about keys and supported operations and algorithms, see the Key Vault documentation.
KeyClient can create keys in the vault, get existing keys from the vault, update key metadata, and delete keys, as shown in the examples below.
This section contains code snippets covering common tasks:
The create_key method can be
used by a KeyClient
to create a key of any type -- alternatively, specific helpers such as
create_rsa_key and
create_ec_key
create RSA and elliptic curve keys in the vault, respectively. If a key with the same name already exists, a new version
of that key is created.
from azure.identity import DefaultAzureCredential
from azure.keyvault.keys import KeyClient
credential = DefaultAzureCredential()
key_client = KeyClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
# Create an RSA key
rsa_key = key_client.create_rsa_key("rsa-key-name", size=2048)
print(rsa_key.name)
print(rsa_key.key_type)
# Create an elliptic curve key
ec_key = key_client.create_ec_key("ec-key-name", curve="P-256")
print(ec_key.name)
print(ec_key.key_type)
get_key retrieves a key previously stored in the Vault.
from azure.identity import DefaultAzureCredential
from azure.keyvault.keys import KeyClient
credential = DefaultAzureCredential()
key_client = KeyClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
key = key_client.get_key("key-name")
print(key.name)
update_key_properties updates the properties of a key previously stored in the Key Vault.
from azure.identity import DefaultAzureCredential
from azure.keyvault.keys import KeyClient
credential = DefaultAzureCredential()
key_client = KeyClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
# we will now disable the key for further use
updated_key = key_client.update_key_properties("key-name", enabled=False)
print(updated_key.name)
print(updated_key.properties.enabled)
begin_delete_key
requests Key Vault delete a key, returning a poller which allows you to wait for the deletion to finish. Waiting is
helpful when the vault has soft-delete enabled, and you want to purge (permanently delete) the key as
soon as possible. When soft-delete is disabled, begin_delete_key
itself is permanent.
from azure.identity import DefaultAzureCredential
from azure.keyvault.keys import KeyClient
credential = DefaultAzureCredential()
key_client = KeyClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
deleted_key = key_client.begin_delete_key("key-name").result()
print(deleted_key.name)
print(deleted_key.deleted_date)
update_key_rotation_policy
can be used by a KeyClient
to configure automatic key rotation for a key by specifying a rotation policy.
from azure.keyvault.keys import KeyRotationLifetimeAction, KeyRotationPolicy, KeyRotationPolicyAction
# Here we set the key's automated rotation policy to rotate the key two months after the key was created.
# If you pass an empty KeyRotationPolicy() as the `policy` parameter, the rotation policy will be set to the
# default policy. Any keyword arguments will update specified properties of the policy.
actions = [KeyRotationLifetimeAction(KeyRotationPolicyAction.rotate, time_after_create="P2M")]
updated_policy = client.update_key_rotation_policy(
"rotation-sample-key", policy=KeyRotationPolicy(), expires_in="P90D", lifetime_actions=actions
)
assert updated_policy.expires_in == "P90D"
In addition, rotate_key allows you to rotate a key on-demand by creating a new version of the given key.
rotated_key = client.rotate_key("rotation-sample-key")
print(f"Rotated the key on-demand; new version is {rotated_key.properties.version}")
list_properties_of_keys lists the properties of all of the keys in the client's vault.
from azure.identity import DefaultAzureCredential
from azure.keyvault.keys import KeyClient
credential = DefaultAzureCredential()
key_client = KeyClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
keys = key_client.list_properties_of_keys()
for key in keys:
# the list doesn't include values or versions of the keys
print(key.name)
CryptographyClient enables cryptographic operations (encrypt/decrypt, wrap/unwrap, sign/verify) using a particular key.
from azure.identity import DefaultAzureCredential
from azure.keyvault.keys import KeyClient
from azure.keyvault.keys.crypto import CryptographyClient, EncryptionAlgorithm
credential = DefaultAzureCredential()
key_client = KeyClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
key = key_client.get_key("key-name")
crypto_client = CryptographyClient(key, credential=credential)
plaintext = b"plaintext"
result = crypto_client.encrypt(EncryptionAlgorithm.rsa_oaep, plaintext)
decrypted = crypto_client.decrypt(result.algorithm, result.ciphertext)
See the package documentation for more details of the cryptography API.
This library includes a complete set of async APIs. To use them, you must first install an async transport, such as aiohttp. See azure-core documentation for more information.
Async clients and credentials should be closed when they're no longer needed. These
objects are async context managers and define async close
methods. For
example:
from azure.identity.aio import DefaultAzureCredential
from azure.keyvault.keys.aio import KeyClient
credential = DefaultAzureCredential()
# call close when the client and credential are no longer needed
client = KeyClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
...
await client.close()
await credential.close()
# alternatively, use them as async context managers (contextlib.AsyncExitStack can help)
client = KeyClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
async with client:
async with credential:
...
create_rsa_key and create_ec_key create RSA and elliptic curve keys in the vault, respectively. If a key with the same name already exists, a new version of the key is created.
from azure.identity.aio import DefaultAzureCredential
from azure.keyvault.keys.aio import KeyClient
credential = DefaultAzureCredential()
key_client = KeyClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
# Create an RSA key
rsa_key = await key_client.create_rsa_key("rsa-key-name", size=2048)
print(rsa_key.name)
print(rsa_key.key_type)
# Create an elliptic curve key
ec_key = await key_client.create_ec_key("ec-key-name", curve="P-256")
print(ec_key.name)
print(ec_key.key_type)
list_properties_of_keys lists the properties of all of the keys in the client's vault.
from azure.identity.aio import DefaultAzureCredential
from azure.keyvault.keys.aio import KeyClient
credential = DefaultAzureCredential()
key_client = KeyClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
keys = key_client.list_properties_of_keys()
async for key in keys:
print(key.name)
See the azure-keyvault-keys
troubleshooting guide
for details on how to diagnose various failure scenarios.
Key Vault clients raise exceptions defined in azure-core. For example, if you try to get a key that doesn't exist in the vault, KeyClient raises ResourceNotFoundError:
from azure.identity import DefaultAzureCredential
from azure.keyvault.keys import KeyClient
from azure.core.exceptions import ResourceNotFoundError
credential = DefaultAzureCredential()
key_client = KeyClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
try:
key_client.get_key("which-does-not-exist")
except ResourceNotFoundError as e:
print(e.message)
This library uses the standard logging library for logging. Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO level.
Detailed DEBUG level logging, including request/response bodies and unredacted
headers, can be enabled on a client with the logging_enable
argument:
from azure.identity import DefaultAzureCredential
from azure.keyvault.keys import KeyClient
import sys
import logging
# Create a logger for the 'azure' SDK
logger = logging.getLogger('azure')
logger.setLevel(logging.DEBUG)
# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)
credential = DefaultAzureCredential()
# This client will log detailed information about its HTTP sessions, at DEBUG level
client = KeyClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential, logging_enable=True)
Similarly, logging_enable
can enable detailed logging for a single operation,
even when it isn't enabled for the client:
client.get_key("my-key", logging_enable=True)
Several samples are available in the Azure SDK for Python GitHub repository. These provide example code for additional Key Vault scenarios:
send_request
client methodFor more extensive documentation on Azure Key Vault, see the API reference documentation.
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
enable_cae=True
is passed to all get_token
requests.azure-core
version to 1.31.07.5
cryptography
library's RSAPrivateKey
and RSAPublicKey
interfaces are now implemented by
KeyVaultRSAPrivateKey
and KeyVaultRSAPublicKey
classes that can use keys managed by Key VaultCryptographyClient
has create_rsa_private_key
and create_rsa_public_key
methods that return a
KeyVaultRSAPrivateKey
and KeyVaultRSAPublicKey
, respectivelyKeyProperties.hsm_platform
to get the underlying HSM platformasyncio
is no longer directly referenced by the library
(#33819)azure-core
version to 1.29.5azure-common
requirement7.5-preview.1
KeyProperties.hsm_platform
to get the underlying HSM platform7.5-preview.1
is now the defaultcryptography
library's RSAPrivateKey
and RSAPublicKey
interfaces are now implemented by
KeyVaultRSAPrivateKey
and KeyVaultRSAPublicKey
classes that can use keys managed by Key VaultCryptographyClient
has create_rsa_private_key
and create_rsa_public_key
methods that return a
KeyVaultRSAPrivateKey
and KeyVaultRSAPublicKey
, respectively7.4
send_request
method that can be used to send custom requests using the
client's existing pipeline (#25172)These changes do not impact the API of stable versions such as 4.7.0. Only code written against a beta version such as 4.8.0b2 may be affected.
7.4
is now the defaultazure-core
version to 1.24.0msrest
version to 0.7.1msrest
requirementsix
requirementisodate>=0.6.1
(isodate
was required by msrest
)typing-extensions>=4.0.1
7.4-preview.1
KeyClient
has a create_okp_key
method to create an octet key pair (OKP) on Managed HSMeddsa
to SignatureAlgorithm
enum to support signing and verifying using an
Edwards-Curve Digital Signature Algorithm (EdDSA) on Managed HSMokp
and okp_hsm
to KeyType
enum for octet key pairsed25519
to KeyCurveName
enum to support use of the Ed25519 Edwards curve7.4-preview.1
is now the defaultmsrest
requirementsix
requirementisodate>=0.6.1
(isodate
was required by msrest
)typing-extensions>=4.0.1
azure-core
version to 1.24.0msrest
version to 0.7.1verify_challenge_resource=False
to client constructors to disable.
See https://aka.ms/azsdk/blog/vault-uri for more information.azure-core
version to 1.24.0CryptographyClient
instance created from this key
(#24446)
vault_url
property of a KeyVaultKeyIdentifier
lifetime_actions
.azure-identity
1.8.0 or newer (#20698)KeyClient
has a get_random_bytes
method for getting a requested number of
random bytes from a managed HSMrelease_key
method to KeyClient
for releasing the private component of a keyexportable
and release_policy
keyword-only arguments to key creation and import
methodsKeyExportEncryptionAlgorithm
enum for specifying an encryption algorithm to be used
in key releaseKeyClient.get_cryptography_client
, which provides a simple way to
create a CryptographyClient
for a key, given its name and optionally a version
(#20621)KeyClient.rotate_key
to rotate a key on-demandKeyClient.update_key_rotation_policy
to update a key's automated rotation policyimmutable
keyword-only argument and property to KeyReleasePolicy
to
support immutable release policies. Once a release policy is marked as immutable, it can no
longer be modified.These changes do not impact the API of stable versions such as 4.4.0. Only code written against a beta version such as 4.5.0b1 may be affected.
KeyClient.update_key_rotation_policy
accepts a required policy
argument
(#22981)version
parameter in KeyClient.release_key
is now a keyword-only argument
(#22981)name
parameter in KeyClient.get_key_rotation_policy
and
KeyClient.update_key_rotation_policy
to key_name
(#22981)azure-keyvault-keys
are now uniformly lower-cased
(#22981)KeyType
now ignores casing during declaration, which resolves a scenario where Key Vault
keys created with non-standard casing could not be fetched with the SDK
(#22797)azure-core
version to 1.20.0CryptographyClient
no longer requires a key version when providing a key ID to its constructor
(though providing a version is still recommended)get_token
calls during challenge
authentication requests now pass in a tenant_id
keyword argument
(#20698). See
https://aka.ms/azsdk/python/identity/tokencredential for more details on how to integrate
this parameter if get_token
is implemented by a custom credential.KeyProperties
model's managed
, exportable
, and
release_policy
properties (#22368)immutable
keyword-only argument and property to KeyReleasePolicy
to support immutable
release policies. Once a release policy is marked as immutable, it can no longer be modified.These changes do not impact the API of stable versions such as 4.4.0. Only code written against a beta version such as 4.5.0b1 may be affected.
data
in KeyReleasePolicy
's constructor to
encoded_policy
azure-core
version to 1.20.0KeyProperties
model's managed
, exportable
, and release_policy
properties (#22368)get_token
calls during challenge
authentication requests now pass in a tenant_id
keyword argument
(#20698)azure-identity
1.7.1 or newer
(#20698)These changes do not impact the API of stable versions such as 4.4.0. Only code written against a beta version such as 4.5.0b1 may be affected.
KeyClient.get_random_bytes
now returns bytes instead of RandomBytes. The RandomBytes class
has been removedversion
keyword-only argument in KeyClient.get_cryptography_client
to
key_version
KeyReleasePolicy.data
to KeyReleasePolicy.encoded_policy
target
parameter in KeyClient.release_key
to target_attestation_token
azure-core
version to 1.15.0KeyClient.get_cryptography_client
, which provides a simple way to create a
CryptographyClient
for a key, given its name and optionally a version
(#20621)KeyClient.rotate_key
to rotate a key on-demandKeyClient.update_key_rotation_policy
to update a key's automated rotation policyCryptographyClient
no longer requires a key version when providing a key ID to its constructor
(though providing a version is still recommended)release_key
method to KeyClient
for releasing the private component of a keyexportable
and release_policy
keyword-only arguments to key creation and import
methodsKeyExportEncryptionAlgorithm
enum for specifying an encryption algorithm to be used
in key releaseThese changes do not impact the API of stable versions such as 4.4.0. Only code written against a beta version such as 4.5.0b1 may be affected.
KeyClient.get_random_bytes
now returns a RandomBytes
model with bytes in a value
property, rather than returning the bytes directly
(#19895)Beginning with this release, this library requires Python 2.7 or 3.6+.
KeyClient
has a get_random_bytes
method for getting a requested number of random
bytes from a managed HSMThis is the last version to support Python 3.5. The next version will require Python 2.7 or 3.6+.
msrest
version to 0.6.21KeyClient
has a create_oct_key
method for creating symmetric keysKeyClient
's create_key
and create_rsa_key
methods now accept a public_exponent
keyword-only argument (#18016)oct_hsm
to KeyType
EncryptionAlgorithm
KeyWrapAlgorithm
CryptographyClient
's encrypt
method accepts iv
and
additional_authenticated_data
keyword argumentsCryptographyClient
's decrypt
method accepts iv
,
additional_authenticated_data
, and authentication_tag
keyword argumentsiv
, aad
, and tag
properties to EncryptResult
CryptographyClient
will perform all operations locally if initialized with
the .from_jwk
factory method
(#16565)six
>=1.12.0CryptographyClient
can perform AES-CBCPAD encryption and decryption locally
(#17762)These changes do not impact the API of stable versions such as 4.3.1. Only code written against a beta version such as 4.4.0b1 may be affected.
parse_key_vault_key_id
and KeyVaultResourceId
have been replaced by a
KeyVaultKeyIdentifier
class, which can be initialized with a key IDCryptographyClient
can perform AES-CBCPAD encryption and decryption locally
(#17762)CryptographyClient
will perform all operations locally if initialized with
the .from_jwk
factory method
(#16565)ImportError
when
performing async operations (#16680)oct_hsm
to KeyType
EncryptionAlgorithm
KeyWrapAlgorithm
CryptographyClient
's encrypt
method accepts iv
and
additional_authenticated_data
keyword argumentsCryptographyClient
's decrypt
method accepts iv
,
additional_authenticated_data
, and authentication_tag
keyword argumentsiv
, aad
, and tag
properties to EncryptResult
parse_key_vault_key_id
that parses out a full ID returned by
Key Vault, so users can easily access the key's name
, vault_url
, and version
.CryptographyClient
operations no longer raise AttributeError
when
the client was constructed with a key ID
(#15608)CryptographyClient
can perform decrypt and sign operations locally
(#9754)x-ms-keyvault-region
and x-ms-keyvault-service-version
headers
are no longer redacted in logging outputCryptographyClient
will no longer perform encrypt or wrap operations when
its key has expired or is not yet validazure-core
version to 1.7.0CustomHookPolicy
through the optional
keyword argument custom_hook_policy
x-ms-client-request-id
azure-common
for multiapi supportimport_key
to KeyOperation
recoverable_days
to CertificateProperties
ApiVersion
enum identifying Key Vault versions supported by this packageKeyClient
instances have a close
method which closes opened sockets. Used
as a context manager, a KeyClient
closes opened sockets on exit.
(#9906)azure.keyvault.keys
defines __version__
msrest
requirement to >=0.6.0KeyVaultErrorException
(#9690)AttributeError
in async CryptographyClient when verifying signatures remotely
(#9734)KeyClient.get_cryptography_client()
and CryptographyClient.get_key()
create_key
now has positional parameters name
and key_type
create_ec_key
and create_rsa_key
now have one positional parameter, name
update_key_properties
now has two positional parameters, name
and
(optional) version
import_key
now has positional parameters name
and key
CryptographyClient
operations return class instances instead of tuples and renamed the following
properties
decrypted_bytes
property of DecryptResult
to plaintext
unwrapped_bytes
property of UnwrapResult
to key
result
property of VerifyResult
to is_valid
UnwrapKeyResult
and WrapKeyResult
classes to UnwrapResult
and WrapResult
list_keys
to list_properties_of_keys
list_key_versions
to list_properties_of_key_versions
delete_key
to begin_delete_key
begin_delete_key
and async delete_key
now return pollers that return a DeletedKey
Key
to KeyVaultKey
KeyVaultKey
properties created
, expires
, and updated
renamed to created_on
,
expires_on
, and updated_on
vault_endpoint
parameter of KeyClient
has been renamed to vault_url
vault_endpoint
has been renamed to vault_url
in all modelsCryptographyClient
returns include key_id
and algorithm
propertiesEnums JsonWebKeyCurveName
, JsonWebKeyOperation
, and JsonWebKeyType
have
been renamed to KeyCurveName
, KeyOperation
, and KeyType
, respectively.
Key
now has attribute properties
, which holds certain properties of the
key, such as version
. This changes the shape of the returned Key
type,
as certain properties of Key
(such as version
) have to be accessed
through the properties
property.
update_key
has been renamed to update_key_properties
The vault_url
parameter of KeyClient
has been renamed to vault_endpoint
The property vault_url
has been renamed to vault_endpoint
in all models
key
argument to import_key
should be an instance of azure.keyvault.keys.JsonWebKey
(#7590)CryptographyClient
methods wrap
and unwrap
are renamed wrap_key
and
unwrap_key
, respectively.CryptographyClient
performs encrypt, verify and wrap operations locally
when its key's public material is available (i.e., when it has keys/get
permission).azure.core.Configuration
from the public API in preparation for a
revamped configuration API. Static create_config
methods have been renamed
_create_config
, and will be removed in a future release.wrap_key
and unwrap_key
from KeyClient
. These are now available
through CryptographyClient
.azure-core
1.0.0b2
pip install azure-core==1.0.0b1 azure-keyvault-keys==4.0.0b1
CryptographyClient
, a client for performing cryptographic operations
(encrypt/decrypt, wrap/unwrap, sign/verify) with a key.Version 4.0.0b1 is the first preview of our efforts to create a user-friendly and Pythonic client library for Azure Key Vault. For more information about preview releases of other Azure SDK libraries, please visit https://aka.ms/azure-sdk-preview1-python.
This library is not a direct replacement for azure-keyvault
. Applications
using that library would require code changes to use azure-keyvault-keys
.
This package's
documentation
and
samples
demonstrate the new API.
azure-keyvault
azure-keyvault-keys
contains a client for key operations,
azure-keyvault-secrets
contains a client for secret operationsazure.keyvault.keys.aio
namespace contains an async equivalent of
the synchronous client in azure.keyvault.keys
azure-identity
credentials
azure-keyvault
features not implemented in this releaseFAQs
Microsoft Azure Key Vault Keys Client Library for Python
We found that azure-keyvault-keys demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
PyPI now allows maintainers to archive projects, improving security and helping users make informed decisions about their dependencies.
Research
Security News
Malicious npm package postcss-optimizer delivers BeaverTail malware, targeting developer systems; similarities to past campaigns suggest a North Korean connection.
Security News
CISA's KEV data is now on GitHub, offering easier access, API integration, commit history tracking, and automated updates for security teams and researchers.