Package tlslite :: Package utils :: Module asn1parser
[hide private]
[frames] | no frames]

Source Code for Module tlslite.utils.asn1parser

 1  # Author: Trevor Perrin 
 2  # Patch from Google adding getChildBytes() 
 3  # 
 4  # See the LICENSE file for legal information regarding use of this file. 
 5   
 6  """Abstract Syntax Notation One (ASN.1) parsing""" 
 7   
 8  from .codec import Parser 
9 10 11 -class ASN1Parser(object):
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
21 - def __init__(self, bytes):
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) #skip Type 29 30 #Get Length 31 self.length = self._getASN1Length(p) 32 33 #Get Value 34 self.value = p.getFixBytes(self.length)
35
36 - def getChild(self, which):
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
48 - def getChildCount(self):
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) # skip Type 61 length = self._getASN1Length(p) 62 p.getFixBytes(length) # skip value 63 count += 1 64 return count
65
66 - def getChildBytes(self, which):
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) #skip Type 80 length = self._getASN1Length(p) 81 p.getFixBytes(length) 82 return p.bytes[markIndex : p.index]
83 84 @staticmethod
85 - def _getASN1Length(p):
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