Skip to content

Commit 639b60f

Browse files
author
James Edington
committed
Add DerObject.__repr__()
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.
1 parent dc99309 commit 639b60f

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

lib/Crypto/Util/asn1.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,21 @@ def _decodeFromStream(self, s, strict):
258258
if p.remaining_data() > 0:
259259
raise ValueError("Unexpected extra data after the DER structure")
260260

261+
def __repr__(self):
262+
tag_octet = self._tag_octet
263+
# is_constructed = bool(tag_octet & 0x20)
264+
is_overridden = bool(tag_octet & 0x80)
265+
is_explicit = hasattr(self, '_inner_tag_octet')
266+
is_seq = hasattr(self, '_seq')
267+
asn1id = tag_octet & 0x1f
268+
args_repr = repr(self.value if (not is_seq) else self._seq)
269+
if is_overridden:
270+
if not is_explicit:
271+
args_repr += ', implicit=%i' % (asn1id, )
272+
else:
273+
args_repr += ', explicit=%i' % (asn1id, )
274+
return '%s(%s)' % (self.__class__.__name__, args_repr)
275+
261276

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

705+
def __repr__(self):
706+
return '%s(%s)' % (self.__class__.__name__, repr(self.payload))
707+
690708

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

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

717+
def __repr__(self):
718+
return '%s()' % (self.__class__.__name__, )
719+
699720

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

909+
def __repr__(self):
910+
return '%s(%s)' % (self.__class__.__name__, repr(self.payload))
911+
888912

889913
class DerSetOf(DerObject):
890914
"""Class to model a DER SET OF.

0 commit comments

Comments
 (0)