python - 如何从 Azure Key Vault 中的证书获取私钥?

标签 python azure x509certificate azure-keyvault key-pair

我在 Azure Key Vault 中有一个证书,我想从中提取私钥。

根据Microsoft Docs :

When a Key Vault certificate is created, an addressable key and secret are also created with the same name. The Key Vault key allows key operations and the Key Vault secret allows retrieval of the certificate value as a secret.

但是,我未能成功从中提取私钥。这是我尝试过的一些 python 代码的示例:

pem_data  = get_secret('https://keyvault.azure.net/', 'x509-cert')
pem_data = '-----BEGIN CERTIFICATE----- ' + pem_data + ' -----END CERTIFICATE-----'
pem_data = pem_data.encode()
key = x509.load_pem_x509_certificate(pem_data,  backend=default_backend())
private_key = key.private_key()

但是,这会出错,提示无法加载证书。

最佳答案

现在有一个 sample对于 azure-keyvault-certificates,显示如何使用 pyOpenSSL 从证书获取私钥:

import base64
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
from cryptography.hazmat.primitives.serialization import pkcs12

vault_url = "https://{vault-name}.vault.azure.net"
cert_name = "certificate name"
credential = DefaultAzureCredential()

secret_client = SecretClient(vault_url=vault_url, credential=credential)
certificate_secret = secret_client.get_secret(name=cert_name)

# Now we can extract the private key and public certificate from the secret using the cryptography
# package.
# This example shows how to parse a certificate in PKCS12 format since it's the default in Key Vault,
# but PEM certificates are supported as well. With a PEM certificate, you could use load_pem_private_key
# in place of load_key_and_certificates.
cert_bytes = base64.b64decode(certificate_secret.value)
private_key, public_certificate, additional_certificates = pkcs12.load_key_and_certificates(
    data=cert_bytes,
    password=None
)

有关 Key Vault 的新 Azure SDK 包(取代 azure-keyvault)的更多文档可以在此处找到:

(我使用 Python 处理 Azure SDK)

关于python - 如何从 Azure Key Vault 中的证书获取私钥?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58313018/

相关文章:

jquery - 将 django-dynamic-formset 与来自 d​​jango-extra-views 的 CreateWithInlinesView 一起使用 - 多个表单集

python - 如何在 pandas 中打开包含多个工作表的 excel 文件?

asp.net-mvc - 如何检测 ASP.NET 站点是否在本地、Azure Web 角色或 Azure 网站中运行?

azure - 在 Azure Web App 上找不到证书(已在某些实例上加载,但在其他实例上未加载)

python - PyCharm 错误 : RuntimeError, Click 将中止进一步执行,因为 Python 3

sql - ALTER FEDERATION SWITCH 操作失败。指定的边界值不存在

Azure 存储 - 使用存储访问策略时限制 SAS 中的 IP

c# - X509Certificate2.使用 NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG 导入

c# - 如何使用私钥获取证书的 base 64 编码值?

python - Ursina Python 引擎 : Lighting, 阴影和光晕效果