Question

I am trying to use pyasn1 to encode an RSA signature, but I'm having a problem with defaulted types in a SEQUENCE. I define two AlgorithmIdentifier types, once where the 'algorithm' component is defaulted, and once where it is set manually on a newly created object. If I instantiate one of each object and then call prettyPrint(), the output looks identical. However, if I BER encode (or DER encode for that matter), the object with the defaulted type seems to be missing the algorithm component.

An example:

from pyasn1.type import univ, namedval, namedtype, tag
from pyasn1.codec.ber import encoder

pkcs1 = univ.ObjectIdentifier('1.2.840.113549.1.1')
md5WithRSAEncryption_id = pkcs1 + univ.ObjectIdentifier((4,))

class AlgorithmIdentifier(univ.Sequence):
    componentType = namedtype.NamedTypes(
            namedtype.NamedType('algorithm', univ.ObjectIdentifier()),
            namedtype.OptionalNamedType('params', univ.Any()))

class AlgorithmIdentifier2(univ.Sequence):
    componentType = namedtype.NamedTypes(
            namedtype.DefaultedNamedType('algorithm', md5WithRSAEncryption_id),
            namedtype.OptionalNamedType('params', univ.Any()))

a = AlgorithmIdentifier()
a.setComponentByName('algorithm', md5WithRSAEncryption_id)
print a.prettyPrint()
print "Encoded: %s" % encoder.encode(a).encode('hex')

a2 = AlgorithmIdentifier2()
a2.setDefaultComponents()
print a2.prettyPrint()
print "Encoded: %s" % encoder.encode(a2).encode('hex')

Output:

$ ./testasn1.py
AlgorithmIdentifier:
 algorithm=1.2.840.113549.1.1.4

Encoded: 300b06092a864886f70d010104

AlgorithmIdentifier2:
 algorithm=1.2.840.113549.1.1.4

Encoded: 3000

What am I doing wrong?

Was it helpful?

Solution

Your code is good. Although setDefaultComponents() call may be omitted.

The reason why you do not see default value in encoding is that a component marked DEFAULT may not be necessarily encoded, even if the sending application provided the same value for this component as the default value is (it is a sender’s option according to X.208).

Actually, there is no difference on the receiving end whether you include the defaulted value in encoding or just omit it. In the later case receiving end would plug-in its default. On the bright side, the amount of traffic is reduced.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top