PageRenderTime 18ms CodeModel.GetById 9ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/gdata/tlslite/utils/ASN1Parser.py

http://radioappz.googlecode.com/
Python | 34 lines | 23 code | 5 blank | 6 comment | 3 complexity | 89fa591f913f9bda159d1cac3318858d MD5 | raw file
 1"""Class for parsing ASN.1"""
 2from compat import *
 3from codec import *
 4
 5#Takes a byte array which has a DER TLV field at its head
 6class ASN1Parser:
 7    def __init__(self, bytes):
 8        p = Parser(bytes)
 9        p.get(1) #skip Type
10
11        #Get Length
12        self.length = self._getASN1Length(p)
13
14        #Get Value
15        self.value = p.getFixBytes(self.length)
16
17    #Assuming this is a sequence...
18    def getChild(self, which):
19        p = Parser(self.value)
20        for x in range(which+1):
21            markIndex = p.index
22            p.get(1) #skip Type
23            length = self._getASN1Length(p)
24            p.getFixBytes(length)
25        return ASN1Parser(p.bytes[markIndex : p.index])
26
27    #Decode the ASN.1 DER length field
28    def _getASN1Length(self, p):
29        firstLength = p.get(1)
30        if firstLength<=127:
31            return firstLength
32        else:
33            lengthLength = firstLength & 0x7F
34            return p.get(lengthLength)