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

How to Get Private Key from Certificate in an Azure Key Vault?

我在 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()

但是,这会报错说它无法加载证书。

您从密钥库中获取的 pem_data 已经是 pem 格式,您只能获取 public 密钥。

pem_data = client.get_secret("https://XX.vault.azure.net/", "XX", "XX")
pem_data = pem_data.value.encode()

cert = load_pem_x509_certificate(pem_data,  backend=default_backend())
public_key = cert.public_key()

如果想获取私钥,可以使用OpenSSL:

import OpenSSL.crypto

pem_data = client.get_secret("https://XX.vault.azure.net/", "XX", "XX")
pem_data = pem_data.value.encode()
crtObj = crypto.load_certificate(crypto.FILETYPE_PEM, pem_data)
pubKeyObject = crtObj.get_pubkey()
priKeyString = crypto.dump_privatekey(crypto.FILETYPE_PEM, pubKeyObject)
print(priKeyString)

注:

请确保您在创建证书时已指明密钥是可导出的。如果策略指示不可导出,则私钥在作为秘密检索时不是值的一部分。详情请参阅 this document

现在有 sample for azure-keyvault-certificates that shows how to get the private key from a certificate using 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-keyvault)的新 Azure SDK 包的更多文档:

(我在 Python 中使用 Azure SDK)