在 pyasn1 中添加标记项的更简单方法

Simpler way to add tagged items in pyasn1

我发现在 pyasn1 中添加明确标记的项目的最佳方法是...明确标记它们。但这看起来过于冗长:

cert['tbsCertificate']['extensions'] = rfc2459.Extensions().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 3))

有没有办法生成一个空值,它可以在不指定标签的情况下放入 extensions 这样的地方?

有更简单的方法。约定是,如果您将 None 分配给复杂 [py]ASN.1 类型的组件,该组件将被实例化但不会有任何值。

>>> cert = rfc2459.Certificate()
>>> print cert.prettyPrint()
Certificate:
>>> cert['tbsCertificate'] = None
>>> print cert.prettyPrint()
Certificate:
 tbsCertificate=TBSCertificate:
>>> cert['tbsCertificate']['extensions'] = None
>>> print cert.prettyPrint()
Certificate:
 tbsCertificate=TBSCertificate:
  extensions=Extensions:
>>> cert['tbsCertificate']['extensions'][0] = None
>>> print cert.prettyPrint()
Certificate:
 tbsCertificate=TBSCertificate:
  extensions=Extensions:
   Extension:
>>> cert['tbsCertificate']['extensions'][0]['extnID'] = '1.3.5.4.3.2'
>>> cert['tbsCertificate']['extensions'][0]['extnValue'] = '\x00\x00'
>>> print cert.prettyPrint()
Certificate:
 tbsCertificate=TBSCertificate:
  extensions=Extensions:
   Extension:
    extnID=1.3.5.4.3.2
    extnValue=0x0000
>>> 

这可以有效地让您从 Python 内置或其他 pyasn1 对象分步构建复合 pyasn1 对象,而无需重复其类型规范。