Search code examples
pythonpassword-encryptionasn.1pbkdf2

How to write ASN1 encoding in python using PyASN INTEGER (1..MAX)?


I am trying to implement some encoding in Python using PyASN libraries. I have to define a class where I should implement the following :

pbkdf2params ::= SEQUENCE {
salt OCTET STRING,
iterationCount INTEGER (1..MAX),
keyLength INTEGER (1..MAX)
}

And the python class I have defined is as follows:

class pbkdf2params(univ.Sequence):
 componentType = namedtype.NamedTypes(
   namedtype.NamedType('salt', univ.OctetString()),
   namedtype.NamedType('iterationCount', univ.integer(1,MAX)), 
   namedtype.NamedType('keyLength', univ.integer(1, MAX))
   )

But I don't think this is correct especially for integer(1..MAX) . What have I missed? What is the MAX value it takes in this case?


Solution

  • You need to add a value range constraint to Integer object like this:

    from pyasn1.type import univ, namedtype, constraint
    
    class Pbkdf2params(univ.Sequence):
        componentType = namedtype.NamedTypes(
            namedtype.NamedType('salt', univ.OctetString()),
            namedtype.NamedType('iterationCount', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(1,MAX)), 
            namedtype.NamedType('keyLength', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, MAX))
        )
    

    Whenever you attempt to initialize Integer with an out-of-range value, an exception will be thrown.