Implement ASN1 structure properly using pyasn1
<p>I am new to ASN1 and  want to implement this structure using pyasn1</p>

<pre><code>   ECPrivateKey ::= SEQUENCE {
   version        INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
   privateKey     OCTET STRING,
   parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
   publicKey  [1] BIT STRING OPTIONAL
   }
</code></pre>

<p>here is the code I am using </p>

<pre><code>from pyasn1.type import univ, namedtype, tag
class ZKey(univ.Sequence):
   componentType = namedtype.NamedTypes(
   namedtype.NamedType('id', univ.Integer()),
   namedtype.NamedType('priv', univ.OctetString()),
   namedtype.OptionalNamedType(
   'ECParam',
   univ.ObjectIdentifier().subtype(
     implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)
      )
    ),
    namedtype.OptionalNamedType(
   'pub', 
   univ.BitString().subtype(
     implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1)
   )))
</code></pre>

<p>upon encoding using this sequence I get result <a href="https://lapo.it/asn1js/#30150201010407666F6F2D62617280032A0305810203A8" rel="nofollow">like</a>, when I want the structure to be something like <a href="https://lapo.it/asn1js/#30770201010420713C94CCA8FF45C600673470C98947440CCEBCA65ED67E90D83CC6EECE721C46A00A06082A8648CE3D030107A14403420004D8409A7A6A074EDBA2723C37C1BFDEF5B65C8266BCD4DA7D4F660379D50B7730E57C1FA668E7BD1A504BA7E1627BFB5CDF61F85AA8C2E7F9DC722D09CC9B131E" rel="nofollow">this</a>. What am I missing? Thank You in advance</p>

<p>I guess in the ASN.1 module you are working with, EXPLICIT tagging mode is the default. So in your pyasn1 code you should use explicit tagging as well. </p>

<p>Here's slightly fixed code that should work as you want:</p>

<pre><code>from pyasn1.type import univ, namedtype, tag
from pyasn1.codec.der.encoder import encode
import base64

class ZKey(univ.Sequence):
   componentType = namedtype.NamedTypes(
       namedtype.NamedType('id', univ.Integer()),
       namedtype.NamedType('priv', univ.OctetString()),
       namedtype.OptionalNamedType(
           'ECParam',
           univ.ObjectIdentifier().subtype(
               explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)
           )
       ),
       namedtype.OptionalNamedType(
           'pub', 
           univ.BitString().subtype(
               explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1)
           )
       )
   )

zKey = ZKey()
zKey['id'] = 123
zKey['priv'] = 'foo bar'
zKey['ECParam'] = '1.3.6.1'
zKey['pub'] = [1,0,1,1]

substrate = encode(zKey)

print(base64.encodebytes(substrate))
</code></pre>

python python-3.x pyasn1