如何从 Python 中的 x.509 证书中删除 CT 扩展?

How do I remove CT extensions from an x.509 certificate in Python?

我正在编写 Python 脚本,我需要在其中确定预证书和叶证书是否匹配。

为此,我需要在删除 SCT(1.3.6.1.4.1.11129.2.4.2) 和 Precert Poison(1.3.6.1.4.1.11129.2) 后比较 Precert 和叶证书的 TBS 证书。 4.3) 扩展。

使用python密码模块,很容易获得TBS证书:

from cryptography import x509
from cryptography.hazmat.backends import default_backend

cert = x509.load_pem_x509_certificate(cert_data_pem, default_backend())

print(cert.tbs_certificate_bytes)

但是我一直无法弄清楚如何删除这些扩展程序。看起来 asn1crypto 可以做到,但似乎可用的文档很少。

删除这些扩展程序的最佳方法是什么?如果可行的话,我很乐意依赖 openssl,因为我已经在脚本中使用它了。

好吧,pyasn1 library 最终奏效了。此代码段解码 TBS 证书并删除两个扩展名,然后 re-encodes 它:

from pyasn1.codec.der.decoder import decode as asn1_decode
from pyasn1.codec.der.encoder import encode as asn1_encode
from pyasn1_modules import rfc5280
from cryptography import x509
from cryptography.hazmat.backends import default_backend

cert = asn1_decode(x509.load_pem_x509_certificate(cert_data_pem, default_backend()).tbs_certificate_bytes, asn1Spec=rfc5280.TBSCertificate())[0]

newExts = [ext for ext in cert["extensions"] if str(ext["extnID"]) not in ("1.3.6.1.4.1.11129.2.4.2", "1.3.6.1.4.1.11129.2.4.3")]
cert["extensions"].clear()
cert["extensions"].extend(newExts)

print(asn1_encode(cert))