Bibliotecas de Azure Key Vault para PythonAzure Key Vault libraries for Python

Azure Key Vault es el sistema de almacenamiento y administración de Azure para las claves de cifrado, los secretos y la administración de certificados.Azure Key Vault is Azure's storage and management system for cryptographic keys, secrets, and certificate management. La API del SDK de Python para Key Vault se divide entre las bibliotecas de cliente y las bibliotecas de administración.The Python SDK API for Key Vault is split between client libraries and management libraries.

Use la biblioteca cliente para:Use the client library to:

  • Acceder, actualizar o eliminar los elementos almacenados en Azure Key Vault.Access, update, or delete items stored in an Azure Key Vault
  • Obtener los metadatos de los certificados almacenados.Get metadata for stored certificates
  • Verificar las firmas con las claves simétricas en Key Vault.Verify signatures against symmetric keys in Key Vault

Use la biblioteca de administración para:Use the management library to:

  • Crear, actualizar o eliminar nuevos almacenes de Key Vault.Create, update, or delete new Key Vault stores
  • Controlar las directivas de acceso de Key Vault.Control vault access policies
  • Enumerar los almacenes por suscripción o grupo de recursos.List vaults by subscription or resource group
  • Comprobar la disponibilidad del nombre del almacén.Check for vault name availability

Instalación de las bibliotecasInstall the libraries

Biblioteca de clienteClient library

pip install azure-keyvault

EjemplosExamples

Los ejemplos siguientes usan la autenticación de entidad de servicio, que es el método de inicio de sesión recomendado para las aplicaciones que se conectan a Azure.The following examples use service principal authentication, which is the recommended sign in method for applications that connect to Azure. Para más información acerca de la autenticación de entidad de servicio, consulte Autenticación con el SDK de Azure para Python.To learn about service principal authentication, see Authenticate with the Azure SDK for Python

Recuperar la parte pública de una clave asimétrica de un almacén:Retrieve the public portion of an asymmetric key from a vault:

from azure.keyvault import KeyVaultClient
from azure.common.credentials import ServicePrincipalCredentials

credentials = ServicePrincipalCredentials(
    client_id = '...',
    secret = '...',
    tenant = '...'
)

client = KeyVaultClient(credentials)

# VAULT_URL must be in the format 'https://<vaultname>.vault.azure.net'
# KEY_VERSION is required, and can be obtained with the KeyVaultClient.get_key_versions(self, vault_url, key_name) API
key_bundle = client.get_key(VAULT_URL, KEY_NAME, KEY_VERSION)
key = key_bundle.key

Recuperar un secreto de un almacén:Retrieve a secret from a vault:

from azure.keyvault import KeyVaultClient
from azure.common.credentials import ServicePrincipalCredentials

credentials = ServicePrincipalCredentials(
    client_id = '...',
    secret = '...',
    tenant = '...'
)

client = KeyVaultClient(credentials)

# VAULT_URL must be in the format 'https://<vaultname>.vault.azure.net'
# SECRET_VERSION is required, and can be obtained with the KeyVaultClient.get_secret_versions(self, vault_url, secret_id) API
secret_bundle = client.get_secret(VAULT_URL, SECRET_ID, SECRET_VERSION)
secret = secret_bundle.value

Biblioteca de administraciónManagement library

pip install azure-mgmt-keyvault

EjemploExample

En el ejemplo siguiente se muestra cómo crear un almacén de claves de Azure Key Vault.The following example shows how to create an Azure Key Vault.

from azure.mgmt.keyvault import KeyVaultManagementClient
from azure.common.credentials import ServicePrincipalCredentials


credentials = ServicePrincipalCredentials(
    client_id = '...',
    secret = '...',
    tenant = '...'
)

# Even when using service principal credentials, a subscription ID is required. For service principals,
# this should be the subscription used to create the service principal. Storing a token like a valid
# subscription ID in code is not recommended and only shown here for example purposes.
SUBSCRIPTION_ID = '...'
client = KeyVaultManagementClient(credentials, SUBSCRIPTION_ID)

# The object ID and organization ID (tenant) of the user, application, or service principal for access policies.
# These values can be found through the Azure CLI or the Portal.
ALLOW_OBJECT_ID = '...'
ALLOW_TENANT_ID = '...'

RESOURCE_GROUP = '...'
VAULT_NAME = '...'

# Vault properties may also be created by using the azure.mgmt.keyvault.models.VaultCreateOrUpdateParameters
# class, rather than a map. 
operation = client.vaults.create_or_update(
    RESOURCE_GROUP,
    VAULT_NAME,
    {
        'location': 'eastus',
        'properties': {
            'sku': {
                'name': 'standard'
            },
            'tenant_id': TENANT_ID,
            'access_policies': [{
                'object_id': OBJECT_ID,
                'tenant_id': ALLOW_TENANT_ID,
                'permissions': {
                    'keys': ['all'],
                    'secrets': ['all']
                }
            }]
        }
    }
)

vault = operation.result()
print(f'New vault URI: {vault.properties.vault_uri}')

EjemplosSamples

Vea la lista completa de ejemplos de Azure Key Vault.View the complete list of Azure Key Vault samples.