Edit

Share via


Quickstart: Azure Key Vault Managed HSM client library for Python

Get started with the Azure Key Vault Managed HSM client library for Python. Managed HSM is a fully managed, highly available, single-tenant, standards-compliant cloud service that enables you to safeguard cryptographic keys for your cloud applications, using FIPS 140-3 Level 3 validated HSMs. For more information on Managed HSM, review the Overview.

In this quickstart, you learn how to access and perform cryptographic operations on keys in a Managed HSM using the Python client library.

Managed HSM client library resources:

API reference documentation | Library source code | Package (PyPI)

Prerequisites

Set up your local environment

This quickstart uses the Azure Identity library with Azure CLI to authenticate to Azure services. Developers can also use Visual Studio Code to authenticate their calls. For more information, see Authenticate the client with Azure Identity client library.

Sign in to Azure

Run the az login command to sign in:

az login

Create a project folder and virtual environment

  1. Create a project folder and navigate to it:

    mkdir mhsm-python-app && cd mhsm-python-app
    
  2. Create and activate a virtual environment:

    python -m venv .venv
    source .venv/bin/activate  # On Windows: .venv\Scripts\activate
    

Install the packages

Install the Azure Identity and Key Vault Keys client libraries:

pip install azure-identity azure-keyvault-keys

Create the sample code

Create a file named mhsm_keys.py with the following code. Replace <hsm-name> with your Managed HSM name, and <key-name> with an existing key name.

from azure.identity import DefaultAzureCredential
from azure.keyvault.keys import KeyClient
from azure.keyvault.keys.crypto import CryptographyClient, EncryptionAlgorithm

# Use DefaultAzureCredential for automatic credential selection
credential = DefaultAzureCredential()

# Connect to Managed HSM - replace with your HSM URI
hsm_uri = "https://<hsm-name>.managedhsm.azure.net"
key_client = KeyClient(vault_url=hsm_uri, credential=credential)

# Get a key reference
key_name = "<key-name>"
print(f"Retrieving key '{key_name}' from Managed HSM...")
key = key_client.get_key(key_name)
print(f"Key retrieved. Key type: {key.key_type}")

# Perform cryptographic operations
crypto_client = CryptographyClient(key, credential)

# Encrypt data
plaintext = b"Hello, Managed HSM!"
print(f"\nOriginal text: {plaintext.decode()}")

encrypt_result = crypto_client.encrypt(EncryptionAlgorithm.rsa_oaep_256, plaintext)
print(f"Encrypted (hex): {encrypt_result.ciphertext.hex()[:64]}...")

# Decrypt data
decrypt_result = crypto_client.decrypt(EncryptionAlgorithm.rsa_oaep_256, encrypt_result.ciphertext)
print(f"Decrypted text: {decrypt_result.plaintext.decode()}")

print("\nDone!")

Run the application

Run the application:

python mhsm_keys.py

You should see output similar to:

Retrieving key 'myrsakey' from Managed HSM...
Key retrieved. Key type: RSA-HSM

Original text: Hello, Managed HSM!
Encrypted (hex): 5a8f3b2c1d4e5f6a7b8c9d0e1f2a3b4c...
Decrypted text: Hello, Managed HSM!

Done!

Understanding the code

Authentication with DefaultAzureCredential

DefaultAzureCredential automatically selects the appropriate credential based on your environment:

Environment Credential used
Azure VMs, App Service, Functions System-assigned or user-assigned managed identity
Azure Kubernetes Service Workload identity
Local development Azure CLI, Visual Studio, or VS Code credentials
CI/CD pipelines Workload identity federation or service principal

The credential checks these sources in order:

  1. Environment variables
  2. Workload identity
  3. Managed identity
  4. Azure CLI
  5. Azure PowerShell
  6. Visual Studio / VS Code credentials

For production workloads in Azure, managed identities are strongly recommended because they eliminate credential management entirely.

Key operations

The KeyClient class provides methods to:

  • Create, get, update, and delete keys
  • List keys and key versions
  • Backup and restore keys

The CryptographyClient class provides cryptographic operations:

  • Encrypt and decrypt data
  • Sign and verify signatures
  • Wrap and unwrap keys

Assign Managed HSM roles

For your application to access keys, assign the appropriate Managed HSM local RBAC role to your managed identity. Replace <vm-name>, <resource-group>, and <hsm-name> with your actual values.

# Get the principal ID of your managed identity
principalId=$(az vm identity show --name <vm-name> --resource-group <resource-group> --query principalId -o tsv)

# Assign the Crypto User role for key operations
az keyvault role assignment create \
    --hsm-name <hsm-name> \
    --role "Managed HSM Crypto User" \
    --assignee $principalId \
    --scope /keys

For more information on roles and permissions, see Managed HSM local RBAC built-in roles.

Clean up resources

When no longer needed, delete the resource group and all related resources:

az group delete --name <resource-group>

Warning

Deleting the resource group puts the Managed HSM into a soft-deleted state. The Managed HSM continues to be billed until it's purged. See Managed HSM soft-delete and purge protection

Next steps