Editar

Partilhar via


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

O Azure Key Vault é o sistema de armazenamento e gerenciamento do Azure para gerenciamento de chaves criptográficas, segredos e certificados.Azure Key Vault is Azure's storage and management system for cryptographic keys, secrets, and certificate management. A API do SDK do Python para o Key Vault é dividida entre as bibliotecas de cliente e as bibliotecas de gerenciamento.The Python SDK API for Key Vault is split between client libraries and management libraries.

Use a biblioteca de clientes para:Use the client library to:

  • Acessar, atualizar ou excluir itens armazenados em um Azure Key VaultAccess, update, or delete items stored in an Azure Key Vault
  • Obter metadados para certificados armazenadosGet metadata for stored certificates
  • Verificar assinaturas em relação às chaves simétricas no key VaultVerify signatures against symmetric keys in Key Vault

Use a biblioteca de gerenciamento para:Use the management library to:

  • Criar, atualizar ou excluir novos armazenamentos do Key VaultCreate, update, or delete new Key Vault stores
  • Controlar as políticas de acesso a cofresControl vault access policies
  • Listar os cofres por assinatura ou grupo de recursosList vaults by subscription or resource group
  • Verificar a disponibilidade dos nomes de cofreCheck for vault name availability

Instalar as bibliotecasInstall the libraries

Biblioteca do clienteClient library

pip install azure-keyvault

ExemplosExamples

Os exemplos a seguir usam a autenticação por entidade de serviço, que é o método de entrada recomendado para aplicativos que se conectam ao Azure.The following examples use service principal authentication, which is the recommended sign in method for applications that connect to Azure. Para saber mais sobre a autenticação por entidade de serviço, consulte Autenticação com o SDK do Azure para PythonTo learn about service principal authentication, see Authenticate with the Azure SDK for Python

Recuperar a parte pública de uma chave assimétrica de um cofre: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 um segredo de um cofre: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 gerenciamentoManagement library

pip install azure-mgmt-keyvault

ExemploExample

O exemplo a seguir mostra como criar um 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}')

ExemplosSamples

Veja a lista completa de exemplos do Azure Key Vault.View the complete list of Azure Key Vault samples.