python - 如何在python中修改PEM格式证书的签名
问题描述
有没有办法用 python 修改 PEM 编码的 x509 证书的签名?
我尝试过使用密码学 python 模块,但似乎 x509 签名属性不可设置。我只能得到它的价值。是否有另一个 python 模块可以更好地用于此目的?
密码学 python 模块文档在这里: https ://cryptography.io/en/latest/x509/reference/#x-509-certificate-object
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import Encoding
import os
#change the signature of the cert
def change_cert_sig(pem_data):
cert = x509.load_pem_x509_certificate(pem_data, default_backend())
#the line below works
print(cert.signature)
#the line below causes an exception "AttributeError: can't set attribute"
cert.set_signature(os.urandom(len(cert.signature))) #set signature to random bytes
return cert.public_bytes(Encoding.PEM)
解决方案
有没有办法用 python 修改 PEM 编码的 x509 证书的签名?
是的。
我不是 Python 人,所以我只能描述要做什么......将证书读入内存。这是来自RFC 5280,附录 A,p的证书的 ASN.1 结构。116(和朋友):
Certificate ::= SEQUENCE {
tbsCertificate TBSCertificate,
signatureAlgorithm AlgorithmIdentifier,
signature BIT STRING }
tbsCertificate
是颁发者(或证书颁发机构)签署的内容。“TBS”的意思是“待签署”。 signature
是发行人的签名结束tbsCertificate
。并signatureAlgorithm
描述使用的签名算法,例如sha256WithRSAEncryption
.
跳到第三个属性,即 one signature BIT STRING
。前 4 个八位字节是 ASN.1 编码的一部分BIT_STRING
。八位字节 5-37 是签名字节。获取签名字节之一并对其进行篡改。类似的东西Byte b = data[6]
,b ^= 0x01
然后data[6] = b
。
由于signature
是证书中的最后一件事,您应该能够篡改文件中最后 32 个字节中的任何一个。最后 32 个字节是签名。(32 个字节假定使用 SHA-256 进行签名)。