gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:09:08 26 4
gpt4 key购买 nike

我在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com