pyasn1 icon indicating copy to clipboard operation
pyasn1 copied to clipboard

Incorrect ordering of elements in DER encoded Sets

Open JoeTakagi opened this issue 7 years ago • 2 comments

When an ASN.1 set is encoded using DER, the elements of that set should be encoded in increasing lexicographic order of their DER encodings. This is a requirement of the DER encoding rules and ensures there is exactly one correct DER encoding of an ASN1 Set with specific content (a special property of DER).

pyasn1 seems to DER encode the contents of a set in the order the elements were added so produces output which is a valid BER encoding but not necessarily valid DER.

from pyasn1.type.univ import Set, OctetString
from binascii import hexlify
from pyasn1.codec.der.encoder import encode

s1 = Set()
s1[0] = OctetString('000000000')
s1[1] = OctetString('1111')
s2 = Set()
s2[0] = OctetString('1111')
s2[1] = OctetString('000000000')

# both of these Sets should have the same DER encoding as they have the same content
# and sets are unordered
print hexlify(encode(s1))
print hexlify(encode(s2))

JoeTakagi avatar Jul 06 '18 10:07 JoeTakagi

Are you sure the ordering is done by the whole serialization, not just by tags?

Here is what Dubuisson has on SET ordering in DER:   The components are encoded in the canonical ascending order of their tag; if the module includes the clause AUTOMATIC TAGS in its header, the order of the specification is kept.

etingof avatar Jul 06 '18 22:07 etingof

You're absolutely right - sorry. I had the encoding for 'set of' mixed up with plain 'set'. As best I can tell, the former orders on the entire encoding whereas the latter uses the tags only - Sorry!

JoeTakagi avatar Jul 09 '18 12:07 JoeTakagi