创建包含较新版本 PyASN1 扩展的 X509 证书时文件无效

Invalid files when creating X509 certificates containing extensions with newer versions of PyASN1

我有一个 python 脚本,用于使用 PyASN1 和 pyasn1_modules 模块生成带有证书扩展的 X509 证书。但是现在我已经将这些模块更新到 pypi 的最新版本(以前它们来自 Ubuntu 14.04 repos),生成的证书不再有效(根据 openssl x509 命令以及 dumpasn1 命令显示先前生成的证书的变化,特别是扩展值不再包装在 OctetString 容器中)。

这是有问题的代码:

from pyasn1.type import univ
from pyasn1.codec.der import encoder as der_encoder
from pyasn1_modules import rfc2459

extn = rfc2459.BasicConstraints()
extn.setComponentByName('cA', True)
extn.setComponentByName('pathLenConstraint', 5)

extn_val = der_encoder.encode(extn)
extension = rfc2459.Extension()
extension.setComponentByName('extnID', '2.5.29.19')
extension.setComponentByName('critical', True)
extension.setComponentByName('extnValue', extn_val)

我尝试将最后一行更改为:

extension.setComponentByName('extnValue', univ.OctetString(extn_val))

从 PyASN1 引发此错误:

Component value is tag-incompatible: OctetString(hexValue='30060101ff020105') vs Any()

最近版本的哪些更改可能导致了这种情况,我如何更正我的代码以使其与这两个模块的新版本兼容(最好保持与以前版本的兼容)。

新版本:pyasn1 0.1.9,和pyasn1_modules 0.0.8

Ubuntu 回购版本:pyasn1 0.1.7 和 pyasn1_modules 0.0.3

Python 版本 2.7

您可能还应该对 OCTET STRING 容器进行编码。

原因是RFC指定它为OCTET STRING,但是pyasn1-modules使用ANY类型。由于ANY类型是透明序列化的(例如不加tag),所以需要通过OCTET STRING序列化。

extension.setComponentByName('extnValue', der_encoder.encode(univ.OctetString(extn_val)))