CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-azure-keyvault

Microsoft Azure Key Vault Client Libraries for Python providing unified access to keys, secrets, and certificates

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

key-management.mddocs/

Key Management

Comprehensive key lifecycle management for cryptographic keys in Azure Key Vault. Supports RSA, Elliptic Curve (EC), and symmetric keys with Hardware Security Module (HSM) backing. Provides key creation, versioning, rotation, backup/restore, and soft-delete recovery capabilities.

# Required imports for long-running operations
from azure.core.polling import LROPoller

Capabilities

Key Client

Main client for key management operations supporting both synchronous and asynchronous usage patterns.

class KeyClient:
    def __init__(self, vault_url: str, credential, **kwargs):
        """
        Initialize KeyClient for key management operations.
        
        Parameters:
        - vault_url: str, Key Vault URL (https://vault-name.vault.azure.net/)
        - credential: Azure credential object for authentication
        - api_version: ApiVersion, API version to use (default: latest)
        - **kwargs: Additional configuration options
        """

    def close(self) -> None:
        """Close the client and release resources."""

Key Creation

Create new cryptographic keys with various algorithms and parameters.

def create_key(self, name: str, key_type: KeyType, **kwargs) -> KeyVaultKey:
    """
    Create a new key in the Key Vault.
    
    Parameters:
    - name: str, unique key name within the vault
    - key_type: KeyType, type of key to create (rsa, ec, oct, etc.)
    - size: int, key size in bits (RSA: 2048, 3072, 4096; EC: 256, 384, 521)
    - curve: KeyCurveName, curve for EC keys (p_256, p_384, p_521, p_256k)  
    - key_operations: List[KeyOperation], allowed operations
    - enabled: bool, whether key is enabled for use
    - expires_on: datetime, expiration date
    - not_before: datetime, activation date
    - tags: Dict[str, str], custom metadata
    - hsm: bool, create HSM-backed key
    
    Returns:
    KeyVaultKey with key metadata and public key material
    """

def create_rsa_key(self, name: str, **kwargs) -> KeyVaultKey:
    """
    Create RSA key with specified size.
    
    Parameters:
    - name: str, unique key name
    - size: int, key size (2048, 3072, 4096)
    - hardware_protected: bool, use HSM backing
    - **kwargs: Additional key properties
    
    Returns:
    KeyVaultKey with RSA key
    """

def create_ec_key(self, name: str, **kwargs) -> KeyVaultKey:
    """
    Create Elliptic Curve key.
    
    Parameters:
    - name: str, unique key name  
    - curve: KeyCurveName, EC curve to use
    - hardware_protected: bool, use HSM backing
    - **kwargs: Additional key properties
    
    Returns:
    KeyVaultKey with EC key
    """

def create_oct_key(self, name: str, **kwargs) -> KeyVaultKey:
    """
    Create symmetric key for AES operations.
    
    Parameters:
    - name: str, unique key name
    - size: int, key size in bits (128, 192, 256)
    - hardware_protected: bool, use HSM backing  
    - **kwargs: Additional key properties
    
    Returns:
    KeyVaultKey with symmetric key
    """

def import_key(self, name: str, key: JsonWebKey, **kwargs) -> KeyVaultKey:
    """
    Import existing key material.
    
    Parameters:
    - name: str, unique key name
    - key: JsonWebKey, key material to import
    - hsm: bool, import to HSM
    - **kwargs: Additional key properties
    
    Returns:
    KeyVaultKey with imported key
    """

Key Retrieval

Retrieve keys and their versions from the vault.

def get_key(self, name: str, version: str = None, **kwargs) -> KeyVaultKey:
    """
    Get a key from the vault.
    
    Parameters:
    - name: str, key name
    - version: str, specific version (default: latest)
    
    Returns:
    KeyVaultKey with key data and metadata
    """

def list_properties_of_keys(**kwargs) -> ItemPaged[KeyProperties]:
    """
    List all keys in the vault.
    
    Parameters:
    - max_page_size: int, maximum items per page
    
    Returns:
    Paginated list of KeyProperties
    """

def list_properties_of_key_versions(self, name: str, **kwargs) -> ItemPaged[KeyProperties]:
    """
    List all versions of a specific key.
    
    Parameters:
    - name: str, key name
    - max_page_size: int, maximum items per page
    
    Returns:
    Paginated list of KeyProperties for all versions
    """

Key Operations

Update, delete, and manage key lifecycle.

def update_key_properties(self, name: str, version: str = None, **kwargs) -> KeyVaultKey:
    """
    Update key properties and metadata.
    
    Parameters:
    - name: str, key name
    - version: str, specific version (default: latest)
    - key_operations: List[KeyOperation], allowed operations
    - enabled: bool, enable/disable key
    - expires_on: datetime, expiration date
    - not_before: datetime, activation date
    - tags: Dict[str, str], custom metadata
    
    Returns:
    KeyVaultKey with updated properties
    """

def begin_delete_key(self, name: str, **kwargs) -> LROPoller[DeletedKey]:
    """
    Delete a key (soft delete) - long-running operation.
    
    Parameters:
    - name: str, key name to delete
    
    Returns:
    LROPoller[DeletedKey] for tracking deletion progress
    """

def get_deleted_key(self, name: str, **kwargs) -> DeletedKey:
    """
    Get properties of a deleted key.
    
    Parameters:
    - name: str, deleted key name
    
    Returns:
    DeletedKey with deletion information
    """

def begin_recover_deleted_key(self, name: str, **kwargs) -> LROPoller[KeyVaultKey]:
    """
    Recover a deleted key - long-running operation.
    
    Parameters:
    - name: str, deleted key name
    
    Returns:
    LROPoller[KeyVaultKey] for tracking recovery progress
    """

def purge_deleted_key(self, name: str, **kwargs) -> None:
    """
    Permanently delete a key.
    
    Parameters:
    - name: str, deleted key name to purge
    """

def list_deleted_keys(**kwargs) -> ItemPaged[DeletedKey]:
    """
    List all deleted keys.
    
    Returns:
    Paginated list of DeletedKey objects
    """

Key Backup and Restore

Backup and restore keys for disaster recovery.

def backup_key(self, name: str, **kwargs) -> bytes:
    """
    Create backup of a key.
    
    Parameters:
    - name: str, key name to backup
    
    Returns:
    bytes containing encrypted backup data
    """

def restore_key_backup(self, backup: bytes, **kwargs) -> KeyVaultKey:
    """
    Restore key from backup.
    
    Parameters:
    - backup: bytes, backup data from backup_key()
    
    Returns:
    KeyVaultKey with restored key
    """

Key Rotation

Manage key rotation policies and operations.

def rotate_key(self, name: str, **kwargs) -> KeyVaultKey:
    """
    Create new version of existing key.
    
    Parameters:
    - name: str, key name to rotate
    
    Returns:
    KeyVaultKey with new version
    """

def get_key_rotation_policy(self, name: str, **kwargs) -> KeyRotationPolicy:
    """
    Get rotation policy for a key.
    
    Parameters:
    - name: str, key name
    
    Returns:
    KeyRotationPolicy with policy details
    """

def update_key_rotation_policy(self, name: str, policy: KeyRotationPolicy, **kwargs) -> KeyRotationPolicy:
    """
    Update key rotation policy.
    
    Parameters:
    - name: str, key name
    - policy: KeyRotationPolicy, new policy configuration
    
    Returns:
    KeyRotationPolicy with updated policy
    """

Advanced Operations

Additional key management capabilities.

def get_random_bytes(self, count: int, **kwargs) -> bytes:
    """
    Generate cryptographically secure random bytes.
    
    Parameters:
    - count: int, number of random bytes (1-128)
    
    Returns:
    bytes containing random data
    """

def release_key(self, name: str, target_attestation_token: str, **kwargs) -> ReleaseKeyResult:
    """
    Release key to authorized environment.
    
    Parameters:
    - name: str, key name
    - target_attestation_token: str, attestation token for target environment
    - version: str, key version
    - algorithm: KeyExportEncryptionAlgorithm, encryption algorithm
    
    Returns:
    ReleaseKeyResult with released key data
    """

def get_cryptography_client(self, key_name: str, **kwargs) -> CryptographyClient:
    """
    Get CryptographyClient for key operations.
    
    Parameters:
    - key_name: str, key to use for crypto operations
    - key_version: str, specific key version
    
    Returns:
    CryptographyClient configured for the key
    """

Key Types and Enumerations

class KeyType(str, Enum):
    """Supported key types."""
    rsa = "RSA"
    rsa_hsm = "RSA-HSM"
    ec = "EC"
    ec_hsm = "EC-HSM"  
    oct = "oct"
    oct_hsm = "oct-HSM"

class KeyCurveName(str, Enum):
    """Elliptic curve names."""
    p_256 = "P-256"
    p_384 = "P-384"
    p_521 = "P-521"
    p_256k = "P-256K"

class KeyOperation(str, Enum):
    """Allowed key operations."""
    encrypt = "encrypt"
    decrypt = "decrypt"
    sign = "sign"
    verify = "verify"
    wrap_key = "wrapKey"
    unwrap_key = "unwrapKey"
    import_key = "import"
    export = "export"

class KeyRotationPolicyAction(str, Enum):
    """Key rotation policy actions."""
    rotate = "rotate"
    notify = "notify"

class KeyExportEncryptionAlgorithm(str, Enum):
    """Encryption algorithms for key export."""
    ckm_rsa_aes_key_wrap = "CKM_RSA_AES_KEY_WRAP"
    rsa_aes_key_wrap_256 = "RSA_AES_KEY_WRAP_256"
    rsa_aes_key_wrap_384 = "RSA_AES_KEY_WRAP_384"

Key Model Classes

class KeyVaultKey:
    """Represents a key stored in Azure Key Vault."""
    id: str
    name: str
    properties: KeyProperties
    key: JsonWebKey
    key_type: KeyType

class JsonWebKey:
    """JSON Web Key representation of key material."""
    kid: str  # Key identifier
    kty: str  # Key type
    key_ops: List[str]  # Key operations
    n: bytes  # RSA modulus
    e: bytes  # RSA public exponent
    d: bytes  # RSA private exponent (for local keys)
    p: bytes  # RSA first prime factor
    q: bytes  # RSA second prime factor
    x: bytes  # EC x coordinate
    y: bytes  # EC y coordinate
    k: bytes  # Symmetric key value
    crv: str  # EC curve name

class KeyProperties:
    """Key metadata and properties."""
    id: str
    name: str
    version: str
    enabled: bool
    expires_on: datetime
    not_before: datetime
    created_on: datetime
    updated_on: datetime
    recovery_level: str
    vault_url: str
    tags: Dict[str, str]

class DeletedKey:
    """Represents a deleted key."""
    id: str
    name: str
    properties: KeyProperties
    key: JsonWebKey
    deleted_on: datetime
    recovery_id: str
    scheduled_purge_date: datetime

class KeyVaultKeyIdentifier:
    """Identifier for Key Vault keys."""
    source_id: str
    vault_url: str
    name: str
    version: str

class KeyRotationPolicy:
    """Key rotation policy configuration."""
    id: str
    lifetime_actions: List[KeyRotationLifetimeAction]
    expires_in: str  # ISO 8601 duration
    created_on: datetime
    updated_on: datetime

class KeyRotationLifetimeAction:
    """Lifetime actions for key rotation."""
    action: KeyRotationPolicyAction
    time_after_create: str  # ISO 8601 duration
    time_before_expiry: str  # ISO 8601 duration

class KeyReleasePolicy:
    """Key release policy."""
    encoded_policy: str
    content_type: str

class ReleaseKeyResult:
    """Result of key release operation."""
    value: str

Usage Examples

Basic Key Management

from azure.keyvault.keys import KeyClient
from azure.identity import DefaultAzureCredential

# Initialize client
credential = DefaultAzureCredential()
client = KeyClient(vault_url="https://vault-name.vault.azure.net/", credential=credential)

# Create RSA key
rsa_key = client.create_rsa_key("my-rsa-key", size=2048)
print(f"Created key: {rsa_key.name} (ID: {rsa_key.id})")

# Create EC key  
ec_key = client.create_ec_key("my-ec-key", curve=KeyCurveName.p_256)

# Get key
retrieved_key = client.get_key("my-rsa-key")
print(f"Key enabled: {retrieved_key.properties.enabled}")

# List all keys
for key_properties in client.list_properties_of_keys():
    print(f"Key: {key_properties.name}")

Key Rotation

from azure.keyvault.keys import KeyRotationPolicy, KeyRotationLifetimeAction

# Create rotation policy
lifetime_action = KeyRotationLifetimeAction(
    action=KeyRotationPolicyAction.rotate,
    time_before_expiry="P30D"  # 30 days before expiry
)

policy = KeyRotationPolicy(
    expires_in="P1Y",  # 1 year
    lifetime_actions=[lifetime_action]
)

# Set rotation policy
client.update_key_rotation_policy("my-key", policy)

# Manual rotation
rotated_key = client.rotate_key("my-key")

Backup and Recovery

# Backup key
backup_data = client.backup_key("important-key")

# Simulate deletion
delete_poller = client.begin_delete_key("important-key")
deleted_key = delete_poller.result()  # Wait for completion

# Restore from backup
restored_key = client.restore_key_backup(backup_data)

# Or recover deleted key
recover_poller = client.begin_recover_deleted_key("important-key")
recovered_key = recover_poller.result()  # Wait for completion

Install with Tessl CLI

npx tessl i tessl/pypi-azure-keyvault

docs

administration.md

certificate-management.md

cryptographic-operations.md

index.md

key-management.md

secret-management.md

tile.json