Skip to content

Commit

Permalink
Add DerObject.__repr__()
Browse files Browse the repository at this point in the history
The base case handles sequences and most primitives.

Special handling was required for `DerOctetString` and `DerBitString`
since they store their value at `.payload` rather than `.value`.

Special handling was required for `DerNull` since its current
constructor takes no argument at all, not even `None`.

This should make "playpenning" around with ASN.1-based formats a lot
more convenient.
  • Loading branch information
James Edington committed May 8, 2023
1 parent dc99309 commit 639b60f
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions lib/Crypto/Util/asn1.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,21 @@ def _decodeFromStream(self, s, strict):
if p.remaining_data() > 0:
raise ValueError("Unexpected extra data after the DER structure")

def __repr__(self):
tag_octet = self._tag_octet
# is_constructed = bool(tag_octet & 0x20)
is_overridden = bool(tag_octet & 0x80)
is_explicit = hasattr(self, '_inner_tag_octet')
is_seq = hasattr(self, '_seq')
asn1id = tag_octet & 0x1f
args_repr = repr(self.value if (not is_seq) else self._seq)
if is_overridden:
if not is_explicit:
args_repr += ', implicit=%i' % (asn1id, )
else:
args_repr += ', explicit=%i' % (asn1id, )
return '%s(%s)' % (self.__class__.__name__, args_repr)


class DerInteger(DerObject):
"""Class to model a DER INTEGER.
Expand Down Expand Up @@ -687,6 +702,9 @@ def __init__(self, value=b'', implicit=None):
"""
DerObject.__init__(self, 0x04, value, implicit, False)

def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, repr(self.payload))


class DerNull(DerObject):
"""Class to model a DER NULL element."""
Expand All @@ -696,6 +714,9 @@ def __init__(self):

DerObject.__init__(self, 0x05, b'', None, False)

def __repr__(self):
return '%s()' % (self.__class__.__name__, )


class DerObjectId(DerObject):
"""Class to model a DER OBJECT ID.
Expand Down Expand Up @@ -885,6 +906,9 @@ def _decodeFromStream(self, s, strict):
if self.payload:
self.value = self.payload[1:]

def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, repr(self.payload))


class DerSetOf(DerObject):
"""Class to model a DER SET OF.
Expand Down

0 comments on commit 639b60f

Please sign in to comment.