• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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"""Class for parsing ASN.1"""
7from .compat import *
8from .codec import *
9
10#Takes a byte array which has a DER TLV field at its head
11class ASN1Parser(object):
12    def __init__(self, bytes):
13        p = Parser(bytes)
14        p.get(1) #skip Type
15
16        #Get Length
17        self.length = self._getASN1Length(p)
18
19        #Get Value
20        self.value = p.getFixBytes(self.length)
21
22    #Assuming this is a sequence...
23    def getChild(self, which):
24        return ASN1Parser(self.getChildBytes(which))
25
26    def getChildBytes(self, which):
27        p = Parser(self.value)
28        for x in range(which+1):
29            markIndex = p.index
30            p.get(1) #skip Type
31            length = self._getASN1Length(p)
32            p.getFixBytes(length)
33        return p.bytes[markIndex : p.index]
34
35    #Decode the ASN.1 DER length field
36    def _getASN1Length(self, p):
37        firstLength = p.get(1)
38        if firstLength<=127:
39            return firstLength
40        else:
41            lengthLength = firstLength & 0x7F
42            return p.get(lengthLength)
43