pythonasn.1pyasn1

Simpler way to add tagged items in pyasn1


The best way I found to add explicitly tagged items in pyasn1 is to... explicitly tag them. But this looks overly verbose:

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

Is there any way to generate an empty value which will fit into a place like extensions without specifying the tag?


Solution

  • There is much simpler approach. The convention is that if you assign None to a component of a complex [py]ASN.1 type, that component would be instantiated but will not have a any value.

    >>> 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
    >>> 
    

    That effectively lets you build composite pyasn1 object from either Python built-in or other pyasn1 objects in steps without having to repeat its type specification.