我希望使用在 Azure Key Vault 中创建并存储的证书来签署字符串。我正在使用微软提供的Python SDK来获取证书。我继续从解码的证书秘密中提取私钥。
在这个庄园中获取私钥是一个问题,因为它不允许我在 CryptographyClient 中使用私钥。我收到一个错误,这是预期的并显示在下面,因为私钥不是 KeyVaultKey 实例。
我面临的错误:
Exception has occurred: ValueError
'key' must be a KeyVaultKey instance or a key ID string
File "C:\Users\P.Markham\OneDrive - Royal Terberg Group B.V\Documents\SSF\init.py", line 31, in <module>
cryptography_client = CryptographyClient(private_key, credential=credential)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: 'key' must be a KeyVaultKey instance or a key ID string
我正在使用的代码如下所示:
import os
import hashlib
import base64
from cryptography.hazmat.primitives.serialization import pkcs12
from azure.identity import DefaultAzureCredential
from azure.keyvault.keys import KeyClient
from azure.keyvault.keys.crypto import SignatureAlgorithm
from azure.keyvault.certificates import CertificateClient
from azure.keyvault.secrets import SecretClient
from azure.keyvault.keys.crypto import CryptographyClient, EncryptionAlgorithm
VAULT_URL = os.environ["AZURE_VAULT_URL"]
CERTIFICATE_NAME = os.environ["AZURE_CERTIFICATE_NAME"]
credential = DefaultAzureCredential()
certificate_client = CertificateClient(vault_url=VAULT_URL, credential=credential)
secret_client = SecretClient(vault_url=VAULT_URL, credential=credential)
certificate_secret = secret_client.get_secret(name=CERTIFICATE_NAME)
cert_bytes = base64.b64decode(certificate_secret.value)
private_key, public_certificate, additional_certificates = pkcs12.load_key_and_certificates(
data=cert_bytes,
password=None
)
print(f"Certificate with name '{certificate_secret.name}' was parsed.")
digest = hashlib.sha256(b"an example string i want to sign").digest()
cryptography_client = CryptographyClient(private_key, credential=credential)
# sign returns the signature and the metadata required to verify it
result = cryptography_client.sign(SignatureAlgorithm.rs256, digest)
print(f"Key ID: {result.key_id}")
print(f"Algorithm: {result.algorithm}")
print(f"Signature: {result.signature}")
signature = result.signature
如何使用证书对字符串进行签名?我觉得我正在以完全错误的方式处理这个问题,但我找不到任何链接签名与证书的文档。
如果你想使用证书来执行加密操作,你可以直接使用同名的密钥——不需要从证书秘密中解析出密钥。例如:
import hashlib
import os
from azure.identity import DefaultAzureCredential
from azure.keyvault.keys import KeyClient
from azure.keyvault.keys.crypto import CryptographyClient, SignatureAlgorithm
VAULT_URL = os.environ["AZURE_VAULT_URL"]
CERTIFICATE_NAME = os.environ["AZURE_CERTIFICATE_NAME"]
credential = DefaultAzureCredential()
key_client = KeyClient(VAULT_URL, credential)
cert_key = key_client.get_key(CERTIFICATE_NAME)
digest = hashlib.sha256(b"an example string i want to sign").digest()
cryptography_client = CryptographyClient(cert_key, credential)
result = cryptography_client.sign(SignatureAlgorithm.rs256, digest)
print(f"Key ID: {result.key_id}")
print(f"Algorithm: {result.algorithm}")
print(f"Signature: {result.signature}")
signature = result.signature