/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"""
  2. from compat import *
  3. from codec import *
  4. #Takes a byte array which has a DER TLV field at its head
  5. class ASN1Parser:
  6. def __init__(self, bytes):
  7. p = Parser(bytes)
  8. p.get(1) #skip Type
  9. #Get Length
  10. self.length = self._getASN1Length(p)
  11. #Get Value
  12. self.value = p.getFixBytes(self.length)
  13. #Assuming this is a sequence...
  14. def getChild(self, which):
  15. p = Parser(self.value)
  16. for x in range(which+1):
  17. markIndex = p.index
  18. p.get(1) #skip Type
  19. length = self._getASN1Length(p)
  20. p.getFixBytes(length)
  21. return ASN1Parser(p.bytes[markIndex : p.index])
  22. #Decode the ASN.1 DER length field
  23. def _getASN1Length(self, p):
  24. firstLength = p.get(1)
  25. if firstLength<=127:
  26. return firstLength
  27. else:
  28. lengthLength = firstLength & 0x7F
  29. return p.get(lengthLength)