快速入门:适用于 Python 的 Azure Key Vault 客户端密钥库Quickstart: Azure Key Vault keys 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. 通过使用 Key Vault 存储加密密钥,可以避免在代码中存储此类密钥,从而提高应用程序的安全性。By using Key Vault to store cryptographic keys, you avoid storing such keys in your code, which increases the security of your app.
API 参考文档 | 库源代码 | 包(Python 包索引)API reference documentation | Library source code | Package (Python Package Index)
先决条件Prerequisites
- Azure 订阅 - 免费创建订阅。An Azure subscription - create one for free.
- Python 2.7+ 或 3.5.3+Python 2.7+ or 3.5.3+
- Azure CLIAzure CLI
本快速入门假设你在 Linux 终端窗口中运行 Azure CLI。This quickstart assumes you are running Azure CLI in a Linux terminal window.
设置本地环境Set up your local environment
本快速入门结合使用 Azure Identity 库和 Azure CLI,向 Azure 服务验证用户身份。This quickstart is using Azure Identity library with Azure CLI to authenticate user to Azure Services. 开发人员还可以使用 Visual Studio 或 Visual Studio Code 来验证其调用。有关详细信息,请参阅使用 Azure Identity 客户端库对客户端进行身份验证。Developers can also use Visual Studio or Visual Studio Code to authenticate their calls, for more information, see Authenticate the client with Azure Identity client library.
登录 AzureSign in to Azure
运行
login
命令。Run thelogin
command.az cloud set -n AzureChinaCloud az login
如果 CLI 可以打开默认浏览器,它将这样做并加载 Azure 登录页。If the CLI can open your default browser, it will do so and load an Azure sign-in page.
否则,请在 https://login.partner.microsoftonline.cn/common/oauth2/deviceauth 处打开浏览器页,然后输入终端中显示的授权代码。Otherwise, open a browser page at https://login.partner.microsoftonline.cn/common/oauth2/deviceauth and enter the authorization code displayed in your terminal.
在浏览器中使用帐户凭据登录。Sign in with your account credentials in the browser.
安装包Install the packages
在终端或命令提示符中,创建合适的项目文件夹,然后创建并激活 Python 虚拟环境,如使用 Python 虚拟环境中所述。In a terminal or command prompt, create a suitable project folder, and then create and activate a Python virtual environment as described on Use Python virtual environments.
安装 Azure Active Directory 标识库:Install the Azure Active Directory identity library:
pip install azure.identity
安装 Key Vault 密钥客户端库:Install the Key Vault key client library:
pip install azure-keyvault-keys
创建资源组和 Key VaultCreate a resource group and key vault
使用
az group create
命令以创建资源组:Use theaz group create
command to create a resource group:az group create --name KeyVault-PythonQS-rg --location chinaeast
如果愿意,你可以将“chinaeast”更改为离你更近的位置。You can change "chinaeast" to a location nearer to you, if you prefer.
使用
az keyvault create
创建密钥保管库:Useaz keyvault create
to create the key vault:az keyvault create --name <your-unique-keyvault-name> --resource-group KeyVault-PythonQS-rg
将
<your-unique-keyvault-name>
替换为在整个 Azure 中均唯一的名称。Replace<your-unique-keyvault-name>
with a name that's unique across all of Azure. 通常使用个人或公司名称以及其他数字和标识符。You typically use your personal or company name along with other numbers and identifiers.创建用于向代码提供 Key Vault 名称的环境变量:Create an environment variable that supplies the name of the Key Vault to the code:
授予对 Key Vault 的访问权限Grant access to your key vault
针对密钥保管库创建一个访问策略,以便为用户帐户授予机密权限。Create an access policy for your key vault that grants secret permission to your user account.
az keyvault set-policy --name <YourKeyVaultName> --upn user@domain.com --secret-permissions delete get list set
设置环境变量Set environment variables
此应用程序使用 Key Vault 名称作为名为 KEY_VAULT_NAME
的环境变量。This application is using key vault name as an environment variable called KEY_VAULT_NAME
.
WindowsWindows
set KEY_VAULT_NAME=<your-key-vault-name>
Windows PowerShellWindows PowerShell
$Env:KEY_VAULT_NAME=<your-key-vault-name>
macOS 或 LinuxmacOS or Linux
export KEY_VAULT_NAME=<your-key-vault-name>
创建示例代码Create the sample code
使用适用于 Python 的 Azure Key Vault 密钥客户端库,你可以管理加密密钥。The Azure Key Vault key client library for Python allows you to manage cryptographic keys. 以下代码示例演示如何创建客户端、设置密钥、检索密钥和删除密钥。The following code sample demonstrates how to create a client, set a key, retrieve a key, and delete a key.
创建包含此代码的名为 kv_keys.py 的文件。Create a file named kv_keys.py that contains this code.
import os
from azure.keyvault.keys 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 = input("Input a name for your key > ")
print(f"Creating a key in {keyVaultName} called '{keyName}' ...")
rsa_key = client.create_rsa_key(keyName, size=2048)
print(" done.")
print(f"Retrieving your key from {keyVaultName}.")
retrieved_key = client.get_key(keyName)
print(f"Key with name '{retrieved_key.name}' was found.")
print(f"Deleting your key from {keyVaultName} ...")
poller = client.begin_delete_key(keyName)
deleted_key = poller.result()
print(" done.")
运行代码Run the code
确保上一部分中的代码位于名为 kv_keys.py 的文件中。Make sure the code in the previous section is in a file named kv_keys.py. 然后,使用以下命令运行代码:Then run the code with the following command:
python kv_keys.py
- 如果遇到权限错误,请确保已运行
az keyvault set-policy
命令。If you encounter permissions errors, make sure you ran theaz keyvault set-policy
command. - 重新运行具有相同密钥名称的代码可能会产生错误:“(冲突)密钥
当前处于已删除但可恢复的状态。” Re-running the code with the same key name may produce the error, "(Conflict) Keyis currently in a deleted but recoverable state." 使用其他密钥名称。Use a different key name.
代码详细信息Code details
进行身份验证并创建客户端Authenticate and create a client
本快速入门使用登录用户向 Key Vault 进行身份验证,这是本地开发的首选方法。In this quickstart, logged in user is used to authenticate to key vault, which is preferred method for local development. 对于部署到 Azure 的应用程序,应将托管标识分配给应用服务或虚拟机。有关详细信息,请参阅托管标识概述。For applications deployed to Azure, managed identity should be assigned to App Service or Virtual Machine, for more information, see Managed Identity Overview.
在下面的示例中,密钥保管库的名称将扩展为密钥保管库 URI,格式为“https://<your-key-vault-name>.vault.azure.cn”。In below example, the name of your key vault is expanded to the key vault URI, in the format "https://<your-key-vault-name>.vault.azure.cn". 此示例使用 'DefaultAzureCredential()' 类,该类允许在具有不同选项的不同环境中使用相同代码提供标识。This example is using 'DefaultAzureCredential()' class, which allows to use the same code across different environments with different options to provide identity. 有关详细信息,请参阅默认 Azure 凭据身份验证。For more information, see Default Azure Credential Authentication.
credential = DefaultAzureCredential()
client = KeyClient(vault_url=KVUri, credential=credential)
保存密钥Save a key
获取密钥保管库的客户端对象后,可以使用 create_rsa_key 方法存储密钥:Once you've obtained the client object for the key vault, you can store a key using the create_rsa_key method:
rsa_key = client.create_rsa_key(keyName, size=2048)
还可以使用 create_key 或 create_ec_key。You can also use create_key or create_ec_key.
调用 create
方法会生成对密钥保管库的 Azure REST API 的调用。Calling a create
method generates a call to the Azure REST API for the key vault.
在处理请求时,Azure 使用你提供给客户端的凭据对象,对调用方的标识(服务主体)进行身份验证。When handling the request, Azure authenticates the caller's identity (the service principal) using the credential object you provided to the client.
检索密钥Retrieve a key
若要读取 Key Vault 中的密钥,请使用 get_key 方法:To read a key from Key Vault, use the get_key method:
retrieved_key = client.get_key(keyName)
还可以使用 Azure CLI 命令 az keyvault key show 来验证是否设置了密钥。You can also verify that the key has been set with the Azure CLI command az keyvault key show.
删除密钥Delete a key
若要删除密钥,请使用 begin_delete_key 方法:To delete a key, use the begin_delete_key method:
poller = client.begin_delete_key(keyName)
deleted_key = poller.result()
begin_delete_key
方法是异步方法,将返回一个轮询器对象。The begin_delete_key
method is asynchronous and returns a poller object. 调用轮询器的 result
方法等待其完成。Calling the poller's result
method waits for its completion.
可以使用 Azure CLI 命令 az keyvault key show 来验证是否已删除密钥。You can verify that the key is deleted with the Azure CLI command az keyvault key show.
删除密钥后,该密钥会在一段时间内保持已删除但可恢复状态。Once deleted, a key remains in a deleted but recoverable state for a time. 如果再次运行该代码,请使用其他密钥名称。If you run the code again, use a different key name.
清理资源Clean up resources
如果还想进行证书和机密相关试验,可以重复使用在本文中创建的 Key Vault。If you want to also experiment with certificates and secrets, you can reuse the Key Vault created in this article.
否则,当完成本文中创建的资源后,请使用以下命令删除资源组及其包含的所有资源:Otherwise, when you're finished with the resources created in this article, use the following command to delete the resource group and all its contained resources:
az group delete --resource-group KeyVault-PythonQS-rg