1
2
3
4
5
6 """Abstract Syntax Notation One (ASN.1) parsing"""
7
8 from .codec import Parser
12 """
13 Parser and storage of ASN.1 DER encoded objects.
14
15 @type length: int
16 @ivar length: length of the value of the tag
17 @type value: bytearray
18 @ivar value: literal value of the tag
19 """
20
22 """Create an object from bytes.
23
24 @type bytes: bytearray
25 @param bytes: DER encoded ANS.1 object
26 """
27 p = Parser(bytes)
28 p.get(1)
29
30
31 self.length = self._getASN1Length(p)
32
33
34 self.value = p.getFixBytes(self.length)
35
37 """
38 Return n-th child assuming that the object is a SEQUENCE.
39
40 @type which: int
41 @param which: ordinal of the child to return
42
43 @rtype: ASN1Parser
44 @return: decoded child object
45 """
46 return ASN1Parser(self.getChildBytes(which))
47
49 """
50 Return number of children, assuming that the object is a SEQUENCE.
51
52 @rtype: int
53 @return number of children in the object
54 """
55 p = Parser(self.value)
56 count = 0
57 while True:
58 if p.getRemainingLength() == 0:
59 break
60 p.get(1)
61 length = self._getASN1Length(p)
62 p.getFixBytes(length)
63 count += 1
64 return count
65
67 """
68 Return raw encoding of n-th child, assume self is a SEQUENCE
69
70 @type which: int
71 @param which: ordinal of the child to return
72
73 @rtype: bytearray
74 @return: raw child object
75 """
76 p = Parser(self.value)
77 for _ in range(which+1):
78 markIndex = p.index
79 p.get(1)
80 length = self._getASN1Length(p)
81 p.getFixBytes(length)
82 return p.bytes[markIndex : p.index]
83
84 @staticmethod
86 """Decode the ASN.1 DER length field"""
87 firstLength = p.get(1)
88 if firstLength <= 127:
89 return firstLength
90 else:
91 lengthLength = firstLength & 0x7F
92 return p.get(lengthLength)
93