CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-azure-keyvault-keys

Microsoft Azure Key Vault Keys client library for Python providing cryptographic key management operations

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

Core key lifecycle operations including creation, retrieval, updating, deletion, and enumeration of cryptographic keys in Azure Key Vault. Supports all Azure Key Vault key types (RSA, EC, symmetric) with both hardware-protected (HSM) and software-protected variants.

Capabilities

Key Creation

Create new cryptographic keys with various types and configurations.

def create_key(
    name: str,
    key_type: KeyType,
    *,
    size: int = None,
    curve: KeyCurveName = None,
    key_operations: List[KeyOperation] = None,
    enabled: bool = None,
    not_before: datetime = None,
    expires_on: datetime = None,
    tags: Dict[str, str] = None,
    **kwargs
) -> KeyVaultKey:
    """
    Create a new key.

    Parameters:
    - name: The name of the key to create
    - key_type: The type of key to create (RSA, EC, oct, etc.)
    - size: Key size in bits (RSA: 2048, 3072, 4096; oct: 128, 192, 256)
    - curve: Elliptic curve for EC keys (P-256, P-384, P-521, P-256K)
    - key_operations: List of permitted operations
    - enabled: Whether the key is enabled
    - not_before: Key not valid before this date
    - expires_on: Key expiration date
    - tags: Application-specific metadata

    Returns:
    KeyVaultKey: The created key with metadata
    """

def create_rsa_key(
    name: str,
    *,
    size: int = None,
    hardware_protected: bool = False,
    key_operations: List[KeyOperation] = None,
    enabled: bool = None,
    not_before: datetime = None,
    expires_on: datetime = None,
    tags: Dict[str, str] = None,
    **kwargs
) -> KeyVaultKey:
    """
    Create an RSA key.

    Parameters:
    - name: The name of the key to create
    - size: RSA key size in bits (2048, 3072, 4096). Default: 2048
    - hardware_protected: Whether to use HSM-backed key (RSA-HSM)
    - key_operations: List of permitted operations
    - enabled: Whether the key is enabled
    - not_before: Key not valid before this date
    - expires_on: Key expiration date
    - tags: Application-specific metadata

    Returns:
    KeyVaultKey: The created RSA key
    """

def create_ec_key(
    name: str,
    *,
    curve: KeyCurveName = None,
    hardware_protected: bool = False,
    key_operations: List[KeyOperation] = None,
    enabled: bool = None,
    not_before: datetime = None,
    expires_on: datetime = None,
    tags: Dict[str, str] = None,
    **kwargs
) -> KeyVaultKey:
    """
    Create an Elliptic Curve key.

    Parameters:
    - name: The name of the key to create
    - curve: Elliptic curve (P-256, P-384, P-521, P-256K). Default: P-256
    - hardware_protected: Whether to use HSM-backed key (EC-HSM)
    - key_operations: List of permitted operations
    - enabled: Whether the key is enabled
    - not_before: Key not valid before this date
    - expires_on: Key expiration date
    - tags: Application-specific metadata

    Returns:
    KeyVaultKey: The created EC key
    """

def create_oct_key(
    name: str,
    *,
    size: int = None,
    hardware_protected: bool = False,
    key_operations: List[KeyOperation] = None,
    enabled: bool = None,
    not_before: datetime = None,
    expires_on: datetime = None,
    tags: Dict[str, str] = None,
    **kwargs
) -> KeyVaultKey:
    """
    Create a symmetric (oct) key.

    Parameters:
    - name: The name of the key to create
    - size: Key size in bits (128, 192, 256). Default: 256
    - hardware_protected: Whether to use HSM-backed key (oct-HSM)
    - key_operations: List of permitted operations
    - enabled: Whether the key is enabled
    - not_before: Key not valid before this date
    - expires_on: Key expiration date
    - tags: Application-specific metadata

    Returns:
    KeyVaultKey: The created symmetric key
    """

Usage Examples

from azure.keyvault.keys import KeyClient, KeyType, KeyCurveName, KeyOperation
from azure.identity import DefaultAzureCredential

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

# Create RSA key with specific operations
rsa_key = client.create_rsa_key(
    "my-rsa-key",
    size=2048,
    key_operations=[KeyOperation.encrypt, KeyOperation.decrypt, KeyOperation.sign, KeyOperation.verify]
)

# Create EC key for signing
ec_key = client.create_ec_key(
    "my-ec-key",
    curve=KeyCurveName.p_256,
    key_operations=[KeyOperation.sign, KeyOperation.verify]
)

# Create symmetric key for encryption
symmetric_key = client.create_oct_key(
    "my-symmetric-key",
    size=256,
    key_operations=[KeyOperation.encrypt, KeyOperation.decrypt]
)

Key Retrieval

Retrieve existing keys and their properties.

def get_key(name: str, version: str = None, **kwargs) -> KeyVaultKey:
    """
    Get a key from the vault.

    Parameters:
    - name: The name of the key to retrieve
    - version: Specific version of the key (optional, gets latest if omitted)

    Returns:
    KeyVaultKey: The key with its properties and cryptographic material
    """

def list_properties_of_keys(**kwargs) -> ItemPaged[KeyProperties]:
    """
    List properties of all keys in the vault.

    Returns:
    ItemPaged[KeyProperties]: Paginated list of key properties (without cryptographic material)
    """

def list_properties_of_key_versions(name: str, **kwargs) -> ItemPaged[KeyProperties]:
    """
    List properties of all versions of a specific key.

    Parameters:
    - name: The name of the key

    Returns:
    ItemPaged[KeyProperties]: Paginated list of key version properties
    """

Usage Examples

# Get latest version of a key
key = client.get_key("my-key")
print(f"Key ID: {key.id}")
print(f"Key Type: {key.key_type}")

# Get specific version of a key
specific_key = client.get_key("my-key", version="abc123...")

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

# List all versions of a specific key
for version_properties in client.list_properties_of_key_versions("my-key"):
    print(f"Version: {version_properties.version}, Created: {version_properties.created_on}")

Key Updates

Update key properties and metadata.

def update_key_properties(
    name: str,
    version: str = None,
    *,
    key_operations: List[KeyOperation] = None,
    enabled: bool = None,
    not_before: datetime = None,
    expires_on: datetime = None,
    tags: Dict[str, str] = None,
    **kwargs
) -> KeyVaultKey:
    """
    Update a key's properties.

    Parameters:
    - name: The name of the key to update
    - version: Specific version to update (optional, updates latest if omitted)
    - key_operations: New list of permitted operations
    - enabled: Whether the key should be enabled
    - not_before: New not-before date
    - expires_on: New expiration date
    - tags: New application-specific metadata

    Returns:
    KeyVaultKey: The updated key
    """

Usage Examples

# Disable a key
updated_key = client.update_key_properties("my-key", enabled=False)

# Update key operations
updated_key = client.update_key_properties(
    "my-key", 
    key_operations=[KeyOperation.sign, KeyOperation.verify]
)

# Add tags and expiration
from datetime import datetime, timedelta
updated_key = client.update_key_properties(
    "my-key",
    tags={"environment": "production", "team": "security"},
    expires_on=datetime.utcnow() + timedelta(days=365)
)

Key Deletion

Delete keys with soft-delete protection.

def begin_delete_key(name: str, **kwargs) -> LROPoller[DeletedKey]:
    """
    Begin deleting a key (soft delete).

    Parameters:
    - name: The name of the key to delete

    Returns:
    LROPoller[DeletedKey]: Long-running operation poller for the deletion
    """

Usage Examples

# Delete a key (soft delete)
delete_poller = client.begin_delete_key("my-key")
deleted_key = delete_poller.result()
print(f"Deleted key: {deleted_key.name}")
print(f"Recovery ID: {deleted_key.recovery_id}")
print(f"Scheduled purge date: {deleted_key.scheduled_purge_date}")

Utility Operations

Additional key management utilities.

def get_random_bytes(count: int, **kwargs) -> bytes:
    """
    Get cryptographically secure random bytes from the Key Vault HSM.

    Parameters:
    - count: Number of random bytes to retrieve (1-128)

    Returns:
    bytes: Cryptographically secure random bytes
    """

def get_cryptography_client(
    key_name: str,
    *,
    key_version: str = None,
    **kwargs
) -> CryptographyClient:
    """
    Get a CryptographyClient for performing cryptographic operations with a specific key.

    Parameters:
    - key_name: Name of the key to use for cryptographic operations
    - key_version: Specific version of the key (optional)

    Returns:
    CryptographyClient: Client for cryptographic operations
    """

Usage Examples

# Get random bytes
random_data = client.get_random_bytes(32)
print(f"Random bytes: {random_data.hex()}")

# Get crypto client for a key
crypto_client = client.get_cryptography_client("my-encryption-key")

Key Attestation

Get attestation information for hardware security module (HSM) backed keys.

def get_key_attestation(
    name: str,
    version: str = None,
    **kwargs
) -> KeyVaultKey:
    """
    Get attestation information for a key.

    Parameters:
    - name: The name of the key
    - version: Specific version of the key (optional, gets latest if omitted)

    Returns:
    KeyVaultKey: The key with attestation information populated

    Raises:
    - ResourceNotFoundError: If the key doesn't exist
    - ForbiddenError: If insufficient permissions to access attestation
    """

Usage Examples

# Get key attestation
key_with_attestation = client.get_key_attestation("my-hsm-key")
if key_with_attestation.properties.attestation:
    print(f"Attestation version: {key_with_attestation.properties.attestation.version}")
    print(f"Certificate available: {key_with_attestation.properties.attestation.certificate_pem_file is not None}")

# Get attestation for specific version
specific_attestation = client.get_key_attestation("my-hsm-key", version="abc123...")

Types

class KeyVaultKey:
    """A key's attributes and cryptographic material."""
    id: str
    name: str
    properties: KeyProperties
    key: JsonWebKey
    key_type: KeyType
    key_operations: List[KeyOperation]

class KeyAttestation:
    """Key attestation information for HSM-backed keys."""
    certificate_pem_file: bytes  # Certificate used for attestation validation (PEM format)
    private_key_attestation: bytes  # Private key attestation
    public_key_attestation: bytes   # Public key attestation  
    version: str                    # Attestation version

class KeyVaultKeyIdentifier:
    """Information about a KeyVaultKey parsed from a key ID."""
    source_id: str   # The complete key identifier URL
    vault_url: str   # The Key Vault URL
    name: str        # The key name
    version: str     # The key version (optional)

class KeyProperties:
    """A key's ID and attributes without cryptographic material."""
    id: str
    name: str
    version: str
    enabled: bool
    not_before: datetime
    expires_on: datetime
    created_on: datetime
    updated_on: datetime
    vault_url: str
    recoverable_days: int
    recovery_level: str
    tags: Dict[str, str]
    managed: bool
    exportable: bool

class JsonWebKey:
    """JSON Web Key representation as defined in RFC 7517."""
    kid: str
    kty: KeyType
    key_ops: List[KeyOperation]
    # RSA parameters
    n: bytes  # RSA modulus
    e: bytes  # RSA public exponent
    d: bytes  # RSA private exponent
    dp: bytes  # RSA private key parameter
    dq: bytes  # RSA private key parameter
    qi: bytes  # RSA private key parameter
    p: bytes  # RSA secret prime
    q: bytes  # RSA secret prime
    # EC parameters
    crv: KeyCurveName  # Elliptic curve name
    x: bytes  # X component of EC public key
    y: bytes  # Y component of EC public key
    # Symmetric key parameters
    k: bytes  # Symmetric key
    # HSM token
    t: bytes  # HSM Token for Bring Your Own Key

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

class KeyCurveName(str, Enum):
    """Supported elliptic curves."""
    p_256 = "P-256"    # NIST P-256 elliptic curve
    p_384 = "P-384"    # NIST P-384 elliptic curve
    p_521 = "P-521"    # NIST P-521 elliptic curve
    p_256_k = "P-256K"  # SECG SECP256K1 elliptic curve

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

Install with Tessl CLI

npx tessl i tessl/pypi-azure-keyvault-keys

docs

async-operations.md

backup-recovery.md

crypto-operations.md

import-export.md

index.md

key-management.md

rotation-policies.md

tile.json