How to prettyprint as hex a pyasn1 octect string that is printed as ascii

877 Views Asked by At

I have some pyasn1 octect string objects defined like this:

LInfo.componentType = namedtype.NamedTypes(namedtype.NamedType('XXX', univ.OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(2, 2)).subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)))

When I decode the asn.1 using pyasn.1 library, it translates the value to its ascii representation, for example I get "&/" but I need to show the numeric value, in hex representation. For example in this case instead of &/ I need 262F. Obviously I can extract &/ or whatever I find in there and convert it manually, like:

value.asOctects().encode("HEX")

but then I can't write it back in the field in this format.

Is there an easy way to manipulate the object before printing it out in such a way that I can see 262F in the final pretty print without modifying the asn.1 definition (that I can't change as it is given to me)?

1

There are 1 best solutions below

1
On BEST ANSWER

What you could do is to subclass the OctetString class, override its prettyPrint method then register your new class with the decoder. What your prettyPrint returns is what ultimately goes out into print.

from pyasn1.codec.ber import decoder
from pyasn1.type import univ


class OctetString(univ.OctetString):
    def prettyPrint(self):
        return self._value


class OctetStringDecoder(decoder.OctetStringDecoder):
    protoComponent = OctetString('')


decoder.tagMap[OctetString.tagSet] = OctetStringDecoder()
decoder.typeMap[OctetString.typeId] = OctetStringDecoder()

Here is the original code.