如何从Azure密钥保管库中的证书中获取私钥?

时间:2019-10-09 22:18:42

标签: python azure x509certificate azure-keyvault key-pair

我在Azure密钥保管库中有一个证书,我想从中提取私钥。

根据Microsoft文档: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()

但是,这将错误地指出它无法加载证书。

2 个答案:

答案 0 :(得分:1)

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

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

enter image description here

答案 1 :(得分:0)

现在有一个 azure-keyvault-certificatessample,显示了如何使用 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)

相关问题