简体   繁体   中英

Implement ASN1 structure properly using pyasn1

I am new to ASN1 and want to implement this structure using pyasn1

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

here is the code I am using

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

upon encoding using this sequence I get result like , when I want the structure to be something like this . What am I missing? Thank You in advance

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.

Here's slightly fixed code that should work as you want:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM