我想计算我的 x509 RootCA 证书公钥的 sha256 哈希值,但是我的结果与标准不符。(RFC)
str(hashlib.sha256(str(crypto.dump_publickey(crypto.FILETYPE_PEM,x509_cert.get_pubkey())).encode('utf-8')).hexdigest())
我做错了什么
提取公钥的 base64 后,这就是使用 python 计算其摘要的方法:
import base64
import hashlib
b64pubkey="MIIBojANBgkqhkiG9w0................."
print(hashlib.sha256(base64.b64decode(b64pubkey)).hexdigest())
使用密码学的完整示例:
from hashlib import sha256
from pathlib import Path
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.x509 import Certificate, load_pem_x509_certificate
def get_cert_pubkey_hash(cert_file: Path) -> str:
"""Compute the SHA256 hash of the public key from a certificate."""
cert_file = Path(cert_file) if isinstance(cert_file, str) else cert_file
with Path(cert_file).open("rb") as cert_file:
cert_data: bytes = cert_file.read()
cert: Certificate = load_pem_x509_certificate(cert_data, default_backend())
public_key_bytes: bytes = cert.public_key().public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
return sha256(public_key_bytes).hexdigest()
print(get_cert_pubkey_hash("/full/path/to/certificate.pem"))