def dec(cls, s, context=None, safe=False): if not safe: return cls.do_dec(s, context, safe) try: return cls.do_dec(s, context, safe) except BER_BadTag_Decoding_Error as e: o, remain = BERcodec_Object.dec(e.remaining, context, safe) return ASN1_BADTAG(o), remain except BER_Decoding_Error as e: return ASN1_DECODING_ERROR(s, exc=e), "" except ASN1_Error as e: return ASN1_DECODING_ERROR(s, exc=e), ""
class BERcodec_Object: __metaclass__ = BERcodec_metaclass codec = ASN1_Codecs.BER tag = ASN1_Class_UNIVERSAL.ANY @classmethod def asn1_object(cls, val): return cls.tag.asn1_object(val) @classmethod def check_string(cls, s): if not s: raise BER_Decoding_Error("%s: Got empty object while expecting tag %r" % (cls.__name__,cls.tag), remaining=s) @classmethod def check_type(cls, s): cls.check_string(s) if cls.tag != ord(s[0]): raise BER_BadTag_Decoding_Error("%s: Got tag [%i/%#x] while expecting %r" % (cls.__name__, ord(s[0]), ord(s[0]),cls.tag), remaining=s) return s[1:] @classmethod def check_type_get_len(cls, s): s2 = cls.check_type(s) if not s2: raise BER_Decoding_Error("%s: No bytes while expecting a length" % cls.__name__, remaining=s) return BER_len_dec(s2) @classmethod def check_type_check_len(cls, s): l,s3 = cls.check_type_get_len(s) if len(s3) < l: raise BER_Decoding_Error("%s: Got %i bytes while expecting %i" % (cls.__name__, len(s3), l), remaining=s) return l,s3[:l],s3[l:] @classmethod def do_dec(cls, s, context=None, safe=False): if context is None: context = cls.tag.context cls.check_string(s) p = ord(s[0]) if p not in context: t = s if len(t) > 18: t = t[:15]+"..." raise BER_Decoding_Error("Unknown prefix [%02x] for [%r]" % (p,t), remaining=s) codec = context[p].get_codec(ASN1_Codecs.BER) return codec.dec(s,context,safe) @classmethod def dec(cls, s, context=None, safe=False): if not safe: return cls.do_dec(s, context, safe) try: return cls.do_dec(s, context, safe) except BER_BadTag_Decoding_Error,e: o,remain = BERcodec_Object.dec(e.remaining, context, safe) return ASN1_BADTAG(o),remain except BER_Decoding_Error, e: return ASN1_DECODING_ERROR(s, exc=e),""
codec = context[p].get_codec(ASN1_Codecs.BER) return codec.dec(s,context,safe) @classmethod def dec(cls, s, context=None, safe=False): if not safe: return cls.do_dec(s, context, safe) try: return cls.do_dec(s, context, safe) except BER_BadTag_Decoding_Error,e: o,remain = BERcodec_Object.dec(e.remaining, context, safe) return ASN1_BADTAG(o),remain except BER_Decoding_Error, e: return ASN1_DECODING_ERROR(s, exc=e),"" except ASN1_Error, e: return ASN1_DECODING_ERROR(s, exc=e),"" @classmethod def safedec(cls, s, context=None): return cls.dec(s, context, safe=True) @classmethod def enc(cls, s): if type(s) is str: return BERcodec_STRING.enc(s) else: return BERcodec_INTEGER.enc(int(s))