如何用Python的cryptography库获取公钥的ASN.1 BIT STRING
问题
我有一个PEM编码的证书,想要提取公钥对应的ASN.1 BIT STRING,用来计算OCSP请求所需的issuerKeyHash。目前用pyca的cryptography库只能拿到DER格式的完整主体公钥信息,想找个简便的内置方法提取,不想自己写解析函数。
当前使用的代码:
from cryptography import x509 from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat with open ("test_issuer.pem","rb") as file: pem_data = file.read() issuer_cert = x509.load_pem_x509_certificate(pem_data) pubkey = issuer_cert.public_key() pubkey_bytes = pubkey.public_bytes(encoding=Encoding.DER, format=PublicFormat.SubjectPublicKeyInfo) print(pubkey_bytes.hex())
当前输出(完整主体公钥信息,共91字节):
3059301306072a8648ce3d020106082a8648ce3d030107034200041306605a1910efd18b382f05719062bea9c63a118124bc3cde6a4959734ecef00129c92573255bca278f5a5f3e403128bd9b9ad9d5517c4f796120e673a9aa9e
通过ASN.1查看器或OpenSSL确认,目标BIT STRING从第25字节开始,期望输出:
041306605a1910efd18b382f05719062bea9c63a118124bc3cde6a4959734ecef00129c92573255bca278f5a5f3e403128bd9b9ad9d5517c4f796120e673a9aa9e
解决方法
cryptography库提供了内置方式直接提取公钥的原始BIT STRING内容,无需手动截取字节。只需在调用public_bytes时,将format参数指定为PublicFormat.Raw,同时encoding用Encoding.Raw即可:
from cryptography import x509 from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat with open("test_issuer.pem", "rb") as file: pem_data = file.read() issuer_cert = x509.load_pem_x509_certificate(pem_data) pubkey = issuer_cert.public_key() # 直接提取公钥的原始BIT STRING内容 pubkey_raw_bytes = pubkey.public_bytes(encoding=Encoding.Raw, format=PublicFormat.Raw) print(pubkey_raw_bytes.hex())
这个方法会自动根据公钥类型(如EC、RSA)返回对应的原始字节数据,正好对应SubjectPublicKeyInfo结构中BIT STRING的内容,完全符合需求。
内容的提问来源于stack exchange,提问作者Bertelemy
相关产品推荐
相关产品推荐

