class SnmprecGrammar(AbstractGrammar): ALNUMS = set(octs2ints(str2octs(ascii_letters + digits))) TAG_MAP = {} SNMP_TYPES = (rfc1902.Gauge32, rfc1902.Integer32, rfc1902.IpAddress, univ.Null, univ.ObjectIdentifier, rfc1902.OctetString, rfc1902.TimeTicks, rfc1902.Opaque, rfc1902.Counter32, rfc1902.Counter64, rfc1905.NoSuchObject, rfc1905.NoSuchInstance, rfc1905.EndOfMibView) for typ in SNMP_TYPES: TAG_MAP[str(sum([x for x in typ.tagSet[0]]))] = typ def build(self, oid, tag, val): if oid and tag: return str2octs('%s|%s|%s\n' % (oid, tag, val)) raise error.SnmpsimError('empty OID/tag <%s/%s>' % (oid, tag)) def parse(self, line): try: oid, tag, value = octs2str(line).strip().split('|', 2) except Exception as exc: raise error.SnmpsimError('broken record <%s>: %s' % (line, exc)) else: if oid and tag: return oid, tag, value raise error.SnmpsimError('broken record <%s>' % line) # helper functions def get_tag_by_type(self, value): for tag, typ in self.TAG_MAP.items(): if typ.tagSet[0] == value.tagSet[0]: return tag raise Exception('error: unknown type of %s' % (value, )) def hexify_value(self, value): if value.tagSet in (univ.OctetString.tagSet, rfc1902.Opaque.tagSet, rfc1902.IpAddress.tagSet): nval = value.asNumbers() for x in nval: if (value.tagSet == rfc1902.IpAddress.tagSet or x not in self.ALNUMS): return ''.join(['%.2x' % x for x in nval])
def valueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): if tagSet[0].tagFormat != tag.tagFormatSimple: raise error.PyAsn1Error('Simple tag format expected') head, tail = substrate[:length], substrate[length:] if not head: raise error.PyAsn1Error('Empty substrate') head = octs2ints(head) oid = () index = 0 substrateLen = len(head) while index < substrateLen: subId = head[index] index += 1 if subId < 128: oid += (subId,) elif subId > 128: # Construct subid from a number of octets nextSubId = subId subId = 0 while nextSubId >= 128: subId = (subId << 7) + (nextSubId & 0x7F) if index >= substrateLen: raise error.SubstrateUnderrunError( 'Short substrate for sub-OID past %s' % (oid,) ) nextSubId = head[index] index += 1 oid += ((subId << 7) + nextSubId,) elif subId == 128: # ASN.1 spec forbids leading zeros (0x80) in OID # encoding, tolerating it opens a vulnerability. See # http://www.cosic.esat.kuleuven.be/publications/article-1432.pdf # page 7 raise error.PyAsn1Error('Invalid octet 0x80 in OID encoding') # Decode two leading arcs if 0 <= oid[0] <= 39: oid = (0,) + oid elif 40 <= oid[0] <= 79: oid = (1, oid[0] - 40) + oid[1:] elif oid[0] >= 80: oid = (2, oid[0] - 80) + oid[1:] else: raise error.PyAsn1Error('Malformed first OID octet: %s' % head[0]) return self._createComponent(asn1Spec, tagSet, oid), tail
def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): if tagSet[0].tagFormat != tag.tagFormatSimple: raise error.PyAsn1Error('Simple tag format expected') head, tail = substrate[:length], substrate[length:] if not head: raise error.PyAsn1Error('Empty substrate') head = octs2ints(head) oid = () index = 0 substrateLen = len(head) while index < substrateLen: subId = head[index] index += 1 if subId < 128: oid += (subId,) elif subId > 128: # Construct subid from a number of octets nextSubId = subId subId = 0 while nextSubId >= 128: subId = (subId << 7) + (nextSubId & 0x7F) if index >= substrateLen: raise error.SubstrateUnderrunError( 'Short substrate for sub-OID past %s' % (oid,) ) nextSubId = head[index] index += 1 oid += ((subId << 7) + nextSubId,) elif subId == 128: # ASN.1 spec forbids leading zeros (0x80) in OID # encoding, tolerating it opens a vulnerability. See # http://www.cosic.esat.kuleuven.be/publications/article-1432.pdf # page 7 raise error.PyAsn1Error('Invalid octet 0x80 in OID encoding') # Decode two leading arcs if 0 <= oid[0] <= 39: oid = (0,) + oid elif 40 <= oid[0] <= 79: oid = (1, oid[0] - 40) + oid[1:] elif oid[0] >= 80: oid = (2, oid[0] - 80) + oid[1:] else: raise error.PyAsn1Error('Malformed first OID octet: %s' % head[0]) return self._createComponent(asn1Spec, tagSet, oid), tail
def valueDecoder(self, substrate, asn1Spec, tagSet=None, length=None, state=None, decodeFun=None, substrateFun=None, **options): if tagSet[0].tagFormat != tag.tagFormatSimple: raise error.PyAsn1Error('Simple tag format expected') for chunk in readFromStream(substrate, length, options): if isinstance(chunk, SubstrateUnderrunError): yield chunk if not chunk: raise error.PyAsn1Error('Empty substrate') chunk = octs2ints(chunk) reloid = () index = 0 substrateLen = len(chunk) while index < substrateLen: subId = chunk[index] index += 1 if subId < 128: reloid += (subId, ) elif subId > 128: # Construct subid from a number of octets nextSubId = subId subId = 0 while nextSubId >= 128: subId = (subId << 7) + (nextSubId & 0x7F) if index >= substrateLen: raise error.SubstrateUnderrunError( 'Short substrate for sub-OID past %s' % (reloid, )) nextSubId = chunk[index] index += 1 reloid += ((subId << 7) + nextSubId, ) elif subId == 128: # ASN.1 spec forbids leading zeros (0x80) in OID # encoding, tolerating it opens a vulnerability. See page 7 of # https://www.esat.kuleuven.be/cosic/publications/article-1432.pdf raise error.PyAsn1Error( 'Invalid octet 0x80 in RELATIVE-OID encoding') yield self._createComponent(asn1Spec, tagSet, reloid, **options)
def parse_tecdsa_pem(name): with open(name, 'r') as file: b64 = "" for line in [x.strip() for x in file.readlines()]: # Remove header and footer if not "-----" in line: b64 = b64 + line res = base64.b64decode(b64) print "======" received_record, rest_of_substrate = decode( res, asn1Spec=ThresholdECPrivateKey()) # for field in received_record: # print('{} is {}'.format(field, received_record[field])) print os2ip(octs2ints(received_record['privateShare'])) print received_record['privateEnc'].prettyPrint() print received_record['pairedPublicEnc'].prettyPrint() pub = received_record['publicKey']
def parse_ecdsa_pem(name): with open(name, 'r') as file: b64 = "" for line in [x.strip() for x in file.readlines()]: # Remove header and footer if not "-----" in line: b64 = b64 + line res = base64.b64decode(b64) print "======" print res # print binascii.hexlify(res) received_record, rest_of_substrate = decode(res, asn1Spec=ECPrivateKey()) for field in received_record: print('{} is {}'.format(field, received_record[field])) priv = os2ip(octs2ints(received_record['privateKey'])) print priv pub = received_record['publicKey'] print pub
def test_octs2ints(self): assert [1, 2, 3] == list(octets.octs2ints(bytes([1, 2, 3])))
def __call__(self, substrate, asn1Spec=None, tagSet=None, length=None, state=stDecodeTag, recursiveFlag=True, substrateFun=None, allowEoo=False): if debug.logger and debug.logger & debug.flagDecoder: debug.logger('decoder called at scope %s with state %d, working with up to %d octets of substrate: %s' % (debug.scope, state, len(substrate), debug.hexdump(substrate))) substrate = ensureString(substrate) # Look for end-of-octets sentinel if allowEoo and self.supportIndefLength: if substrate.startswith(self.__eooSentinel): debug.logger and debug.logger & debug.flagDecoder and debug.logger('end-of-octets sentinel found') return eoo.endOfOctets, substrate[2:] value = base.noValue fullSubstrate = substrate while state != stStop: if state == stDecodeTag: if not substrate: raise error.SubstrateUnderrunError( 'Short octet stream on tag decoding' ) # Decode tag isShortTag = True firstOctet = substrate[0] substrate = substrate[1:] try: lastTag = self.__tagCache[firstOctet] except KeyError: integerTag = oct2int(firstOctet) tagClass = integerTag & 0xC0 tagFormat = integerTag & 0x20 tagId = integerTag & 0x1F if tagId == 0x1F: isShortTag = False lengthOctetIdx = 0 tagId = 0 try: while True: integerTag = oct2int(substrate[lengthOctetIdx]) lengthOctetIdx += 1 tagId <<= 7 tagId |= (integerTag & 0x7F) if not integerTag & 0x80: break substrate = substrate[lengthOctetIdx:] except IndexError: raise error.SubstrateUnderrunError( 'Short octet stream on long tag decoding' ) lastTag = tag.Tag( tagClass=tagClass, tagFormat=tagFormat, tagId=tagId ) if isShortTag: # cache short tags self.__tagCache[firstOctet] = lastTag if tagSet is None: if isShortTag: try: tagSet = self.__tagSetCache[firstOctet] except KeyError: # base tag not recovered tagSet = tag.TagSet((), lastTag) self.__tagSetCache[firstOctet] = tagSet else: tagSet = tag.TagSet((), lastTag) else: tagSet = lastTag + tagSet state = stDecodeLength debug.logger and debug.logger & debug.flagDecoder and debug.logger( 'tag decoded into %s, decoding length' % tagSet) if state == stDecodeLength: # Decode length if not substrate: raise error.SubstrateUnderrunError( 'Short octet stream on length decoding' ) firstOctet = oct2int(substrate[0]) if firstOctet < 128: size = 1 length = firstOctet elif firstOctet == 128: size = 1 length = -1 else: size = firstOctet & 0x7F # encoded in size bytes encodedLength = octs2ints(substrate[1:size + 1]) # missing check on maximum size, which shouldn't be a # problem, we can handle more than is possible if len(encodedLength) != size: raise error.SubstrateUnderrunError( '%s<%s at %s' % (size, len(encodedLength), tagSet) ) length = 0 for lengthOctet in encodedLength: length <<= 8 length |= lengthOctet size += 1 substrate = substrate[size:] if length == -1: if not self.supportIndefLength: raise error.PyAsn1Error('Indefinite length encoding not supported by this codec') else: if len(substrate) < length: raise error.SubstrateUnderrunError('%d-octet short' % (length - len(substrate))) state = stGetValueDecoder debug.logger and debug.logger & debug.flagDecoder and debug.logger( 'value length decoded into %d, payload substrate is: %s' % (length, debug.hexdump(length == -1 and substrate or substrate[:length])) ) if state == stGetValueDecoder: if asn1Spec is None: state = stGetValueDecoderByTag else: state = stGetValueDecoderByAsn1Spec # # There're two ways of creating subtypes in ASN.1 what influences # decoder operation. These methods are: # 1) Either base types used in or no IMPLICIT tagging has been # applied on subtyping. # 2) Subtype syntax drops base type information (by means of # IMPLICIT tagging. # The first case allows for complete tag recovery from substrate # while the second one requires original ASN.1 type spec for # decoding. # # In either case a set of tags (tagSet) is coming from substrate # in an incremental, tag-by-tag fashion (this is the case of # EXPLICIT tag which is most basic). Outermost tag comes first # from the wire. # if state == stGetValueDecoderByTag: try: concreteDecoder = self.__tagMap[tagSet] except KeyError: concreteDecoder = None if concreteDecoder: state = stDecodeValue else: try: concreteDecoder = self.__tagMap[tagSet[:1]] except KeyError: concreteDecoder = None if concreteDecoder: state = stDecodeValue else: state = stTryAsExplicitTag if debug.logger and debug.logger & debug.flagDecoder: debug.logger('codec %s chosen by a built-in type, decoding %s' % (concreteDecoder and concreteDecoder.__class__.__name__ or "<none>", state == stDecodeValue and 'value' or 'as explicit tag')) debug.scope.push( concreteDecoder is None and '?' or concreteDecoder.protoComponent.__class__.__name__) if state == stGetValueDecoderByAsn1Spec: if asn1Spec.__class__ is dict or asn1Spec.__class__ is tagmap.TagMap: try: chosenSpec = asn1Spec[tagSet] except KeyError: chosenSpec = None if debug.logger and debug.logger & debug.flagDecoder: debug.logger('candidate ASN.1 spec is a map of:') for firstOctet, v in asn1Spec.presentTypes.items(): debug.logger(' %s -> %s' % (firstOctet, v.__class__.__name__)) if asn1Spec.skipTypes: debug.logger('but neither of: ') for firstOctet, v in asn1Spec.skipTypes.items(): debug.logger(' %s -> %s' % (firstOctet, v.__class__.__name__)) debug.logger('new candidate ASN.1 spec is %s, chosen by %s' % (chosenSpec is None and '<none>' or chosenSpec.prettyPrintType(), tagSet)) else: if tagSet == asn1Spec.tagSet or tagSet in asn1Spec.tagMap: chosenSpec = asn1Spec debug.logger and debug.logger & debug.flagDecoder and debug.logger( 'candidate ASN.1 spec is %s' % asn1Spec.__class__.__name__) else: chosenSpec = None if chosenSpec is not None: try: # ambiguous type or just faster codec lookup concreteDecoder = self.__typeMap[chosenSpec.typeId] debug.logger and debug.logger & debug.flagDecoder and debug.logger( 'value decoder chosen for an ambiguous type by type ID %s' % (chosenSpec.typeId,)) except KeyError: # use base type for codec lookup to recover untagged types baseTagSet = tag.TagSet(chosenSpec.tagSet.baseTag, chosenSpec.tagSet.baseTag) try: # base type or tagged subtype concreteDecoder = self.__tagMap[baseTagSet] debug.logger and debug.logger & debug.flagDecoder and debug.logger( 'value decoder chosen by base %s' % (baseTagSet,)) except KeyError: concreteDecoder = None if concreteDecoder: asn1Spec = chosenSpec state = stDecodeValue else: state = stTryAsExplicitTag else: concreteDecoder = None state = stTryAsExplicitTag if debug.logger and debug.logger & debug.flagDecoder: debug.logger('codec %s chosen by ASN.1 spec, decoding %s' % (state == stDecodeValue and concreteDecoder.__class__.__name__ or "<none>", state == stDecodeValue and 'value' or 'as explicit tag')) debug.scope.push(chosenSpec is None and '?' or chosenSpec.__class__.__name__) if state == stTryAsExplicitTag: if tagSet and tagSet[0].tagFormat == tag.tagFormatConstructed and tagSet[0].tagClass != tag.tagClassUniversal: # Assume explicit tagging concreteDecoder = explicitTagDecoder state = stDecodeValue else: concreteDecoder = None state = self.defaultErrorState debug.logger and debug.logger & debug.flagDecoder and debug.logger('codec %s chosen, decoding %s' % (concreteDecoder and concreteDecoder.__class__.__name__ or "<none>", state == stDecodeValue and 'value' or 'as failure')) if state == stDumpRawValue: concreteDecoder = self.defaultRawDecoder debug.logger and debug.logger & debug.flagDecoder and debug.logger( 'codec %s chosen, decoding value' % concreteDecoder.__class__.__name__) state = stDecodeValue if state == stDecodeValue: if not recursiveFlag and not substrateFun: # legacy def substrateFun(a, b, c): return a, b[:c] if length == -1: # indef length value, substrate = concreteDecoder.indefLenValueDecoder( fullSubstrate, substrate, asn1Spec, tagSet, length, stGetValueDecoder, self, substrateFun ) else: value, substrate = concreteDecoder.valueDecoder( fullSubstrate, substrate, asn1Spec, tagSet, length, stGetValueDecoder, self, substrateFun ) state = stStop debug.logger and debug.logger & debug.flagDecoder and debug.logger( 'codec %s yields type %s, value:\n%s\n...remaining substrate is: %s' % (concreteDecoder.__class__.__name__, value.__class__.__name__, value.prettyPrint(), substrate and debug.hexdump(substrate) or '<none>')) if state == stErrorCondition: raise error.PyAsn1Error( '%s not in asn1Spec: %s' % (tagSet, asn1Spec) ) if debug.logger and debug.logger & debug.flagDecoder: debug.scope.pop() debug.logger('decoder left scope %s, call completed' % debug.scope) return value, substrate
def setUp(self): self.pythonString = ints2octs(self.initializer).decode(self.encoding) self.encodedPythonString = self.pythonString.encode(self.encoding) self.numbersString = tuple(octs2ints(self.encodedPythonString))
def __call__(self, substrate, asn1Spec=None, tagSet=None, length=None, state=stDecodeTag, recursiveFlag=1, substrateFun=None, allowEoo=False): if debug.logger & debug.flagDecoder: debug.logger( 'decoder called at scope %s with state %d, working with up to %d octets of substrate: %s' % (debug.scope, state, len(substrate), debug.hexdump(substrate))) substrate = ensureString(substrate) value = base.noValue fullSubstrate = substrate while state != stStop: if state == stDecodeTag: if not substrate: raise error.SubstrateUnderrunError( 'Short octet stream on tag decoding') # Decode tag firstOctet = substrate[0] substrate = substrate[1:] try: lastTag = self.__tagCache[firstOctet] except KeyError: firstOctet = oct2int(firstOctet) # Look for end-of-octets sentinel if firstOctet == 0: if substrate and oct2int(substrate[0]) == 0: if allowEoo and self.supportIndefLength: debug.logger and debug.logger & debug.flagDecoder and debug.logger( 'end-of-octets sentinel found') value, substrate = eoo.endOfOctets, substrate[ 1:] state = stStop continue else: raise error.PyAsn1Error( 'Unexpected end-of-contents sentinel') else: raise error.PyAsn1Error('Zero tag encountered') tagClass = firstOctet & 0xC0 tagFormat = firstOctet & 0x20 tagId = firstOctet & 0x1F isShortTag = True if tagId == 0x1F: isShortTag = False lengthOctetIdx = 0 tagId = 0 try: while True: firstOctet = oct2int(substrate[lengthOctetIdx]) lengthOctetIdx += 1 tagId <<= 7 | (firstOctet & 0x7F) if not firstOctet & 0x80: break substrate = substrate[lengthOctetIdx:] except IndexError: raise error.SubstrateUnderrunError( 'Short octet stream on long tag decoding') lastTag = tag.Tag(tagClass=tagClass, tagFormat=tagFormat, tagId=tagId) if isShortTag: # cache short tags self.__tagCache[firstOctet] = lastTag if tagSet is None: try: tagSet = self.__tagSetCache[firstOctet] except KeyError: # base tag not recovered tagSet = tag.TagSet((), lastTag) if firstOctet in self.__tagCache: self.__tagSetCache[firstOctet] = tagSet else: tagSet = lastTag + tagSet state = stDecodeLength debug.logger and debug.logger & debug.flagDecoder and debug.logger( 'tag decoded into %s, decoding length' % tagSet) if state == stDecodeLength: # Decode length if not substrate: raise error.SubstrateUnderrunError( 'Short octet stream on length decoding') firstOctet = oct2int(substrate[0]) if firstOctet < 128: size = 1 length = firstOctet elif firstOctet == 128: size = 1 length = -1 else: size = firstOctet & 0x7F # encoded in size bytes encodedLength = octs2ints(substrate[1:size + 1]) # missing check on maximum size, which shouldn't be a # problem, we can handle more than is possible if len(encodedLength) != size: raise error.SubstrateUnderrunError( '%s<%s at %s' % (size, len(encodedLength), tagSet)) length = 0 for lengthOctet in encodedLength: length <<= 8 length |= lengthOctet size += 1 substrate = substrate[size:] if length == -1: if not self.supportIndefLength: raise error.PyAsn1Error( 'Indefinite length encoding not supported by this codec' ) else: if len(substrate) < length: raise error.SubstrateUnderrunError( '%d-octet short' % (length - len(substrate))) state = stGetValueDecoder debug.logger and debug.logger & debug.flagDecoder and debug.logger( 'value length decoded into %d, payload substrate is: %s' % (length, debug.hexdump(length == -1 and substrate or substrate[:length]))) if state == stGetValueDecoder: if asn1Spec is None: state = stGetValueDecoderByTag else: state = stGetValueDecoderByAsn1Spec # # There're two ways of creating subtypes in ASN.1 what influences # decoder operation. These methods are: # 1) Either base types used in or no IMPLICIT tagging has been # applied on subtyping. # 2) Subtype syntax drops base type information (by means of # IMPLICIT tagging. # The first case allows for complete tag recovery from substrate # while the second one requires original ASN.1 type spec for # decoding. # # In either case a set of tags (tagSet) is coming from substrate # in an incremental, tag-by-tag fashion (this is the case of # EXPLICIT tag which is most basic). Outermost tag comes first # from the wire. # if state == stGetValueDecoderByTag: try: concreteDecoder = self.__tagMap[tagSet] except KeyError: concreteDecoder = None if concreteDecoder: state = stDecodeValue else: try: concreteDecoder = self.__tagMap[tagSet[:1]] except KeyError: concreteDecoder = None if concreteDecoder: state = stDecodeValue else: state = stTryAsExplicitTag if debug.logger and debug.logger & debug.flagDecoder: debug.logger( 'codec %s chosen by a built-in type, decoding %s' % (concreteDecoder and concreteDecoder.__class__.__name__ or "<none>", state == stDecodeValue and 'value' or 'as explicit tag')) debug.scope.push( concreteDecoder is None and '?' or concreteDecoder.protoComponent.__class__.__name__) if state == stGetValueDecoderByAsn1Spec: if asn1Spec.__class__ is dict or asn1Spec.__class__ is tagmap.TagMap: try: chosenSpec = asn1Spec[tagSet] except KeyError: chosenSpec = None if debug.logger and debug.logger & debug.flagDecoder: debug.logger('candidate ASN.1 spec is a map of:') for firstOctet, v in asn1Spec.posMap.items(): debug.logger(' %s -> %s' % (firstOctet, v.__class__.__name__)) if asn1Spec.negMap: debug.logger('but neither of: ') for firstOctet, v in asn1Spec.negMap.items(): debug.logger( ' %s -> %s' % (firstOctet, v.__class__.__name__)) debug.logger( 'new candidate ASN.1 spec is %s, chosen by %s' % (chosenSpec is None and '<none>' or chosenSpec.prettyPrintType(), tagSet)) else: chosenSpec = asn1Spec debug.logger and debug.logger & debug.flagDecoder and debug.logger( 'candidate ASN.1 spec is %s' % asn1Spec.__class__.__name__) if chosenSpec is not None and ( tagSet == chosenSpec.getTagSet() or tagSet in chosenSpec.getTagMap()): # use base type for codec lookup to recover untagged types baseTagSet = chosenSpec.baseTagSet try: # ambiguous type concreteDecoder = self.__typeMap[chosenSpec.typeId] debug.logger and debug.logger & debug.flagDecoder and debug.logger( 'value decoder chosen for an ambiguous type by type ID %s' % (chosenSpec.typeId, )) except KeyError: try: # base type or tagged subtype concreteDecoder = self.__tagMap[baseTagSet] debug.logger and debug.logger & debug.flagDecoder and debug.logger( 'value decoder chosen by base %s' % (baseTagSet, )) except KeyError: concreteDecoder = None if concreteDecoder: asn1Spec = chosenSpec state = stDecodeValue else: state = stTryAsExplicitTag else: concreteDecoder = None state = stTryAsExplicitTag if debug.logger and debug.logger & debug.flagDecoder: debug.logger( 'codec %s chosen by ASN.1 spec, decoding %s' % (state == stDecodeValue and concreteDecoder.__class__.__name__ or "<none>", state == stDecodeValue and 'value' or 'as explicit tag')) debug.scope.push(chosenSpec is None and '?' or chosenSpec.__class__.__name__) if state == stTryAsExplicitTag: if tagSet and tagSet[ 0].tagFormat == tag.tagFormatConstructed and tagSet[ 0].tagClass != tag.tagClassUniversal: # Assume explicit tagging concreteDecoder = explicitTagDecoder state = stDecodeValue else: concreteDecoder = None state = self.defaultErrorState debug.logger and debug.logger & debug.flagDecoder and debug.logger( 'codec %s chosen, decoding %s' % (concreteDecoder and concreteDecoder.__class__.__name__ or "<none>", state == stDecodeValue and 'value' or 'as failure')) if state == stDumpRawValue: concreteDecoder = self.defaultRawDecoder debug.logger and debug.logger & debug.flagDecoder and debug.logger( 'codec %s chosen, decoding value' % concreteDecoder.__class__.__name__) state = stDecodeValue if state == stDecodeValue: if not recursiveFlag and not substrateFun: # legacy def substrateFun(a, b, c): return a, b[:c] if length == -1: # indef length value, substrate = concreteDecoder.indefLenValueDecoder( fullSubstrate, substrate, asn1Spec, tagSet, length, stGetValueDecoder, self, substrateFun) else: value, substrate = concreteDecoder.valueDecoder( fullSubstrate, substrate, asn1Spec, tagSet, length, stGetValueDecoder, self, substrateFun) state = stStop debug.logger and debug.logger & debug.flagDecoder and debug.logger( 'codec %s yields type %s, value:\n%s\n...remaining substrate is: %s' % (concreteDecoder.__class__.__name__, value.__class__.__name__, value.prettyPrint(), substrate and debug.hexdump(substrate) or '<none>')) if state == stErrorCondition: raise error.PyAsn1Error('%s not in asn1Spec: %s' % (tagSet, asn1Spec)) if debug.logger and debug.logger & debug.flagDecoder: debug.scope.pop() debug.logger('decoder left scope %s, call completed' % debug.scope) return value, substrate
def hexdump(octets): return ' '.join( ['%s%.2X' % (n % 16 == 0 and ('\n%.5d: ' % n) or '', x) for n, x in zip(range(len(octets)), octs2ints(octets))] )
def test_octs2ints_empty(self): assert not octets.octs2ints('')
def hexdump(octets): return " ".join( ["%s%.2X" % (n % 16 == 0 and ("\n%.5d: " % n) or "", x) for n, x in zip(range(len(octets)), octs2ints(octets))] )
def test_octs2ints_empty(self): assert not octets.octs2ints(bytes([]))
def test_octs2ints(self): assert [1, 2, 3] == octets.octs2ints('\x01\x02\x03')
def hexdump(octets): return ' '.join( [ '%s%.2X' % (n%16 == 0 and ('\n%.5d: ' % n) or '', x) for n,x in zip(list(range(len(octets))), octs2ints(octets)) ] )