快速入门:适用于 Python 的 Azure Key Vault 客户端库Quickstart: Azure Key Vault client library for Python

适用于 Python 的 Azure Key Vault 客户端库入门。Get started with the Azure Key Vault client library for Python. 请遵循以下步骤安装包并试用基本任务的示例代码。Follow the steps below to install the package and try out example code for basic tasks.

Azure 密钥保管库可帮助保护云应用程序和服务使用的加密密钥和机密。Azure Key Vault helps safeguard cryptographic keys and secrets used by cloud applications and services. 使用适用于 Python 的 Key Vault 客户端库可以:Use the Key Vault client library for Python to:

  • 提高安全性以及控制密钥和密码。Increase security and control over keys and passwords.
  • 在几分钟内创建并导入加密密钥。Create and import encryption keys in minutes.
  • 通过云扩展和全局冗余减少延迟。Reduce latency with cloud scale and global redundancy.
  • 简化和自动化与 TLS/SSL 证书相关的任务。Simplify and automate tasks for TLS/SSL certificates.

API 参考文档 | 库源代码 | 包(Python 包索引)API reference documentation | Library source code | Package (Python Package Index)

先决条件Prerequisites

本快速入门假设你在 Linux 终端窗口中运行 Azure CLIThis quickstart assumes you are running Azure CLI in a Linux terminal window.

设置Setting up

安装包Install the package

在控制台窗口中,安装适用于 Python 的 Azure Key Vault 密钥库。From the console window, install the Azure Key Vault keys library for Python.

pip install azure-keyvault-keys

本快速入门还需要安装 azure.identity 包:For this quickstart, you will need to install the azure.identity package as well:

pip install azure.identity

创建资源组和 Key VaultCreate a resource group and key vault

本快速入门使用预先创建的 Azure Key Vault。This quickstart uses a pre-created Azure key vault. 可以遵循 Azure CLI 快速入门Azure PowerShell 快速入门Azure 门户快速入门中的步骤创建 Key Vault。You can create a key vault by following the steps in the Azure CLI quickstart, Azure PowerShell quickstart, or Azure portal quickstart. 或者,可运行以下 Azure CLI 命令。Alternatively, you can run the Azure CLI commands below.

Important

每个密钥保管库必须具有唯一的名称。Each key vault must have a unique name. 在以下示例中,将 替换为密钥保管库的名称。Replace with the name of your key vault in the following examples.

az group create --name "myResourceGroup" -l "ChinaEast"

az keyvault create --name <your-unique-keyvault-name> -g "myResourceGroup"

创建服务主体Create a service principal

对基于云的 .NET 应用程序进行身份验证的最简单方法是使用托管标识;有关详细信息,请参阅使用应用服务托管标识访问 Azure Key VaultThe simplest way to authenticate a cloud-based .NET application is with a managed identity; see Use an App Service managed identity to access Azure Key Vault for details.

不过,为了简单起见,本快速入门创建了一个需要使用服务主体和访问控制策略的桌面应用程序。For the sake of simplicity however, this quickstart creates a desktop application, which requires the use of a service principal and an access control policy. 服务主体要求使用格式为“http://<my-unique-service-principle-name>”的唯一名称。Your service principle requires a unique name in the format "http://<my-unique-service-principle-name>".

使用 Azure CLI az ad sp create-for-rbac 命令创建服务主体:Create a service principle using the Azure CLI az ad sp create-for-rbac command:

az ad sp create-for-rbac -n "http://&lt;my-unique-service-principle-name&gt;" --sdk-auth

此操作将返回一系列键/值对。This operation will return a series of key / value pairs.

{
  "clientId": "7da18cae-779c-41fc-992e-0527854c6583",
  "clientSecret": "b421b443-1669-4cd7-b5b1-394d5c945002",
  "subscriptionId": "443e30da-feca-47c4-b68f-1636b75e16b3",
  "tenantId": "35ad10f1-7799-4766-9acf-f2d946161b77",
  "activeDirectoryEndpointUrl": "https://login.chinacloudapi.cn",
  "resourceManagerEndpointUrl": "https://management.chinacloudapi.cn/",
  "sqlManagementEndpointUrl": "https://management.core.chinacloudapi.cn:8443/",
  "galleryEndpointUrl": "https://gallery.chinacloudapi.cn/",
  "managementEndpointUrl": "https://management.core.chinacloudapi.cn/"
}

请记下 clientId 和 clientSecret,因为在下面的设置环境变量步骤中将要用到。Take note of the clientId and clientSecret, as we will use them in the Set environmental variable step below.

为服务主体授予对 Key Vault 的访问权限Give the service principal access to your key vault

通过将 clientId 传递给 az keyvault set-policy 命令,为密钥保管库创建授予服务主体权限的访问策略。Create an access policy for your key vault that grants permission to your service principal by passing the clientId to the az keyvault set-policy command. 授予服务主体对密钥的 get、list 和 create 权限。Give the service principal get, list, and create permissions for keys.

az keyvault set-policy -n <your-unique-keyvault-name> --spn <clientId-of-your-service-principal> --key-permissions delete get list create 

设置环境变量Set environmental variables

应用程序中的 DefaultAzureCredential 方法依赖于三个环境变量:AZURE_CLIENT_IDAZURE_CLIENT_SECRETAZURE_TENANT_IDThe DefaultAzureCredential method in our application relies on three environmental variables: AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID. 请使用 export VARNAME=VALUE 格式将这些变量设置为在上述创建服务主体步骤中记下的 clientId、clientSecret 和 tenantId 值。Set these variables to the clientId, clientSecret, and tenantId values you noted in the Create a service principal step using the export VARNAME=VALUE format. (该方法只为当前 shell 和从 shell 创建的进程设置变量;若要将这些变量永久添加到环境中,请编辑 /etc/environment 文件。)(This method only sets the variables for your current shell and processes created from the shell; to permanently add these variables to your environment, edit your /etc/environment file.)

还需要将密钥保管库名称另存为名为 KEY_VAULT_NAME 的环境变量。You will also need to save your key vault name as an environment variable called KEY_VAULT_NAME.

export AZURE_CLIENT_ID=<your-clientID>

export AZURE_CLIENT_SECRET=<your-clientSecret>

export AZURE_TENANT_ID=<your-tenantId>

export KEY_VAULT_NAME=<your-key-vault-name>

对象模型Object model

使用适用于 Python 的 Azure Key Vault 客户端库,你可以管理密钥和相关的资产(例如证书和机密)。The Azure Key Vault client library for Python allows you to manage keys and related assets such as certificates and secrets. 以下代码示例展示了如何创建客户端,以及如何创建、检索和删除密钥。The code samples below will show you how to create a client, create a key, retrieve a key, and delete a key.

代码示例Code examples

添加指令Add directives

将以下指令添加到代码的顶部:Add the following directives to the top of your code:

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

进行身份验证并创建客户端Authenticate and create a client

向密钥保管库进行身份验证和创建密钥保管库客户端,依赖于上面设置环境变量步骤中的环境变量。Authenticating to your key vault and creating a key vault client depends on the environmental variables in the Set environmental variables step above. 密钥保管库的名称将扩展为密钥保管库 URI,格式为“https://.vault.azure.cn”。The name of your key vault is expanded to the key vault URI, in the format "https://.vault.azure.cn".

credential = DefaultAzureCredential()

client = KeyClient(vault_url=KVUri, credential=credential)

保存密钥Save a key

现在,应用程序已进行身份验证,可以将密钥放入 keyvault 中了Now that your application is authenticated, you can put a key into your keyvault

rsa_key = client.create_rsa_key(myKey,size=2048)

可以使用 az keyvault key show 命令来验证是否设置了密钥:You can verify that the key has been set with the az keyvault key show command:

az keyvault key show --vault-name <your-unique-keyvault-name> --name myKey

检索密钥Retrieve a key

现在可以检索之前创建的密钥You can now retrieve the previously created key

retrieved_key = client.get_key(keyName)
print(retrieve_key.name)

你的密钥现在保存为 retrieved_keyYour key is now saved as retrieved_key.

删除密钥Delete a key

最后,从密钥保管库中删除密钥Finally, let's delete the key from your key vault

client.delete_key(keyName)

可以使用 az keyvault key show 命令来验证密钥是否已删除:You can verify that the key is gone with the az keyvault key show command:

az keyvault key show --vault-name <your-unique-keyvault-name> --name myKey

清理资源Clean up resources

可以使用 Azure CLI 或 Azure PowerShell 来删除不再需要的 Key Vault 和相应的资源组。When no longer needed, you can use the Azure CLI or Azure PowerShell to remove your key vault and the corresponding resource group.

az group delete -g "myResourceGroup"
Remove-AzResourceGroup -Name "myResourceGroup"

示例代码Sample code

import os
from azure.keyvault.key import KeyClient
from azure.identity import DefaultAzureCredential

keyVaultName = os.environ["KEY_VAULT_NAME"]
KVUri = "https://" + keyVaultName + ".vault.azure.cn"

credential = DefaultAzureCredential()
client = KeyClient(vault_url=KVUri, credential=credential)

keyName = "myKey"

print("Creating a key in " + keyVaultName + " called '" + keyName  + "` ...")

rsa_key = client.create_rsa_key(myKey,size=2048)

print(" done.")

print("Retrieving your key from " + keyVaultName + ".")

retrieved_key = client.get_key(keyName)

print("Key with name '{0}' was found'.".format(retrieved_key.name))
print("Deleting your key from " + keyVaultName + " ...")

client.begin_delete_key(keyName).result()

print(" done.")

后续步骤Next steps

在本快速入门中,你创建了一个密钥保管库,存储了一个密钥,然后检索了该密钥。In this quickstart you created a key vault, stored a key, and retrieved that key. 若要详细了解 Key Vault 以及如何将其与应用程序集成,请继续阅读以下文章。To learn more about Key Vault and how to integrate it with your applications, continue on to the articles below.