U BB`?@sdZddlmZmZmZmZddlmZmZddlm Z ddl Z ddl Z ddl Z ddl Z ddlZddlmZddlmZdd lmZdd lmZmZmZmZmZdd lmZmZdd lmZm Z m!Z!m"Z"m#Z#m$Z$ej%d krddl&m'Z(e)Z*dZ+nddl,m(Z(dZ+e-dddddZ.dddddddddZ/dddZ0e 1dZ2iZ3dddZ4Gd d!d!e5Z6Gd"d#d#Z7Gd$d%d%e5Z8Gd&d'd'e5Z9Gd(d)d)e6Z:e:Z;Gd*d+d+e6ZGd0d1d1e6Z?Gd2d3d3e9e?Z@Gd4d5d5e?ZAGd6d7d7e?e7ZBGd8d9d9e5ZCGd:d;d;eCe9e8e?e7ZDGdd?d?eCe9e8e?ZFGd@dAdAe9e8e?ZGGdBdCdCe9e8e?ZHGdDdEdEe9e8e?ZIGdFdGdGeIZJGdHdIdIe?ZKGdJdKdKe?e7ZLGdLdMdMe?ZMGdNdOdOe?ZNGdPdQdQe?ZOGdRdSdSeBZPGdTdUdUe@ZQGdVdWdWeLZRGdXdYdYe6ZSGdZd[d[e6ZTGd\d]d]eSZUGd^d_d_eTZVGd`dadaeSZWGdbdcdce@ZXGdddedee@ZYGdfdgdge@ZZGdhdidieGZ[Gdjdkdke@Z\Gdldmdme@Z]Gdndodoe]Z^Gdpdqdqe]Z_Gdrdsdse@Z`Gdtdudue@ZaGdvdwdwe@ZbGdxdydye@ZcGdzd{d{e@ZdGd|d}d}e@Zed~dZfddZgddZhddZiddZjeAeBeDeGeKeLeMeNeOePeWeQeReSeUeXeYeZe[e\e^e_e`eaebecedeedZkdddZldddZmdS)a ASN.1 type classes for universal types. Exports the following items: - load() - Any() - Asn1Value() - BitString() - BMPString() - Boolean() - CharacterString() - Choice() - EmbeddedPdv() - Enumerated() - GeneralizedTime() - GeneralString() - GraphicString() - IA5String() - InstanceOf() - Integer() - IntegerBitString() - IntegerOctetString() - Null() - NumericString() - ObjectDescriptor() - ObjectIdentifier() - OctetBitString() - OctetString() - PrintableString() - Real() - RelativeOid() - Sequence() - SequenceOf() - Set() - SetOf() - TeletexString() - UniversalString() - UTCTime() - UTF8String() - VideotexString() - VisibleString() - VOID - Void() Other type classes are defined that help compose the types listed above. )unicode_literalsdivisionabsolute_importprint_function)datetime timedelta)FractionN)_teletex_codec)unwrap) OrderedDict) type_namestr_clsbyte_cls int_typeschr_cls)_parse _dump_header) int_to_bytesint_from_bytestimezoneextended_datetimecreate_timezone utc_with_dst))StringIOT)BytesIOF universal applicationcontextprivate)rr rr!r)rrrr rr r!r primitive constructedrr z ^\d+(\.\d+)*$cCstj||dS)a5 Loads a BER/DER-encoded byte string and construct a universal object based on the tag value: - 1: Boolean - 2: Integer - 3: BitString - 4: OctetString - 5: Null - 6: ObjectIdentifier - 7: ObjectDescriptor - 8: InstanceOf - 9: Real - 10: Enumerated - 11: EmbeddedPdv - 12: UTF8String - 13: RelativeOid - 16: Sequence, - 17: Set - 18: NumericString - 19: PrintableString - 20: TeletexString - 21: VideotexString - 22: IA5String - 23: UTCTime - 24: GeneralizedTime - 25: GraphicString - 26: VisibleString - 27: GeneralString - 28: UniversalString - 29: CharacterString - 30: BMPString :param encoded_data: A byte string of BER or DER-encoded data :param strict: A boolean indicating if trailing data should be forbidden - if so, a ValueError will be raised when trailing data exists :raises: ValueError - when strict is True and trailing data is present ValueError - when the encoded value tag a tag other than listed above ValueError - when the ASN.1 header length is longer than the data TypeError - when encoded_data is not a byte string :return: An instance of the one of the universal classes )strict) Asn1Valueload) encoded_datar%r)^C:\Users\shjeevan\PycharmProjects\Verisk-XactWare\venv3.8\Lib\site-packages\asn1crypto/core.pyr'ss3r'c @seZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ ed$ddZd%ddZd d Zd d Zd dZddZddZddZddZddZd&ddZddZddZd'd d!Zd(d"d#ZdS))r&z' The basis of all ASN.1 values NFcKsDt|tstdt|d}|jdk r,|}t||||d\}}|S)a Loads a BER/DER-encoded byte string using the current class as the spec :param encoded_data: A byte string of BER or DER-encoded data :param strict: A boolean indicating if trailing data should be forbidden - if so, a ValueError will be raised when trailing data exists :return: An instance of the current class *encoded_data must be a byte string, not %sNspec spec_paramsr%) isinstancer TypeErrorr tag _parse_build)clsr(r%kwargsr.value_r)r)r*r's  zAsn1Value.loadc  Csz8|jtkrR|j} | jdk r8t| jdtr8| jf| _t| drJ|dt| <|dk rt|trx|dkrpd}||f}|dkrd}d}|dk rt|tr|dkrd}||f}|dkrd}d}|dk r |dkrd}|dkr||f}n$|dkr||f}nttdt ||dk rt |d kr8t|d tr8|f}|D]\}}d} t|trd|t krz|} n|t krr|} t |}| dk rttd t | |dk rt|tst td t||jdkr||ff|_n|j||ff|_q <%s %s %s>N)rRr idr@dumprUr)r)r*__repr__szAsn1Value.__repr__cCs|dS)z A fall-back method for print() in Python 2 :return: A byte string of the output of repr() utf-8)r[encoderUr)r)r*rSszAsn1Value.__bytes__cCs|S)z A fall-back method for print() in Python 3 :return: A unicode string of the output of repr() )r[rUr)r)r*rTszAsn1Value.__unicode__cCs,|}|j|_|j|_|j|_|j|_|S)z Constructs a new copy of the current object, preserving any tagging :return: An Asn1Value object )r<rDr2r:r9rInew_objr)r)r* _new_instances zAsn1Value._new_instancecCs|}||tj|S)z Implements the copy.copy() interface :return: A new shallow copy of the current Asn1Value object )r`_copycopyr^r)r)r*__copy__szAsn1Value.__copy__cCs&|}||t|<||tj|S)z Implements the copy.deepcopy() interface :param memo: A dict for memoization :return: A new deep copy of the current Asn1Value object )r`rYrarbdeepcopyrImemor_r)r)r* __deepcopy__s  zAsn1Value.__deepcopy__cCs t|S)z} Copies the object, preserving any special tagging from it :return: An Asn1Value object rbrdrUr)r)r*rbszAsn1Value.copycCs>t|ts||i}|j|d|dd}||tj|S)a} Copies the object, applying a new tagging to it :param tagging: A dict containing the keys "explicit" and "implicit". Legacy API allows a unicode string of "implicit" or "explicit". :param tag: A integer tag number. Only used when tagging is a unicode string. :return: An Asn1Value object r9r:)r9r:)r0dictr<getrarbrd)rIZtaggingr2r_r)r)r*retags  zAsn1Value.retagcCs|}||tj|S)z{ Copies the object, removing any special tagging from it :return: An Asn1Value object )r<rarbrdr^r)r)r*untag/szAsn1Value.untagcCs<|j|jkr$ttdt|t||j|_||j|_dS)a! Copies the contents of another Asn1Value object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects Q Can not copy values from %s object to %s object N)r<r1r r rG_nativerIother copy_funcr)r)r*ra;s zAsn1Value._copyr cCsd|}t|d}t|||r2|j|dnVt|drN|j|dn:trvt|jtrvt d|t |jfnt d||jfdS)J Show the binary data and parsed data in a tree structure  parsedr!chosenz%s Native: b%sz%s Native: %sN) r> _basic_debugrtdebugrurRr0nativerprintr@)rI nest_levelprefixZ has_parsedr)r)r*rwSs   zAsn1Value.debugcCs|j}|jdk r&|jdddkr&d}|jdks4|rt|trJ|jrJd|_t|j|j|j|j}|j dk r|j D] \}}t|d|||j|}qp||_d|_ |j||j S) Encodes the value using DER :param force: If the encoded contents already exist, clear them and regenerate to ensure they are in DER format instead of BER format :return: A byte string of the DER-encoded value NTrr r+) rG_headerr0 Constructable _indefiniterFrrDr2r9_trailer)rIforcerGheaderrDr2r)r)r*rZis  zAsn1Value.dump)F) NNFNNNNNNN)N)r )F)__name__ __module__ __qualname____doc__rFrDr2_bad_tagr:r9rrGrrn classmethodr'rOrVr[rSrTr`rcrgrbrkrlrarwrZr)r)r)r*r&sB  O       r&c@s eZdZdZdZdZddZdS)ValueMapzl Basic functionality that allows for mapping values from ints or OIDs to python unicode strings NcCsF|j}|jdks|jdk rdSi|_|jD]\}}||j|<q.dS)2 Generates _reverse_map from _map N)r<_map _reverse_mapitems)rIr4keyr6r)r)r*r8s zValueMap._setup)rrrrrrr8r)r)r)r*rsrc@seZdZdZddZdS)Castablez A mixin to handle converting an object between different classes that represent the same encoded value, but with different rules for converting to and from native Python values cCs|j|jjkr0ttdt|t||j|jj|}|j|_|j|_|j|_|j|_|j |_ |j |_ t |t r|j |_ |j|_|S)a+ Converts the current object into an object of a different class. The new class must use the ASN.1 encoding for the value. :param other_class: The class to instantiate the new object from :return: An instance of the type other_class z Can not covert a value from %s object to %s object since they use different tags: %d versus %d )r2r<r1r r rDr:r9rrGrr0rrFr)rIZ other_classr_r)r)r*casts&   z Castable.castN)rrrrrr)r)r)r*rsrcs<eZdZdZdZddZddZddZfd d ZZ S) rz A mixin to handle string types that may be constructed from chunks contained within an indefinite length BER-encoded container FcCsr|js|Sd}t|j}d}||kr^t|j||jd\}}|dkrP|}q ||7}q |dkrn|S|S)zc :return: A concatenation of the native values of the contained chunks rN)r.)r _as_chunkrArGr3r< _merge_chunks)rIpointer contents_lenoutputZ sub_valuer)r)r*rs  zConstructable._merge_chunkscCs|jS)a A method to return a chunk of data that can be combined for constructed method values :return: A native Python value that can be added together. Examples include byte strings, unicode strings or tuples. rGrUr)r)r*rs zConstructable._as_chunkcCs|jS)a Returns a native value that can be round-tripped into .set(), to result in a DER encoding. This differs from .native in that .native is designed for the end use, and may account for the fact that the merged value is further parsed as ASN.1, such as in the case of ParsableOctetString() and ParsableOctetBitString(). :return: A python value that is valid to pass to .set() rxrUr)r)r*_setable_natives zConstructable._setable_nativecs*tt||||jr&||dS)a% Copies the contents of another Constructable object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects N)superrrarrError<r)r*ras zConstructable._copy) rrrrrrrrra __classcell__r)r)rr*rs  rc@sJeZdZdZdZddZddZddZd d Ze d d Z dddZ dS)Voidz A representation of an optional value that is not present. Has .native property and .dump() method to be compatible with other value classes. r+cCs |j|jkS)u :param other: The other Primitive to compare to :return: A boolean rrIrpr)r)r*__eq__+s z Void.__eq__cCsdS)NFr)rUr)r)r* __nonzero__6szVoid.__nonzero__cCsdSNrr)rUr)r)r*__len__9sz Void.__len__cCstdS)Nr))iterrUr)r)r*__iter__<sz Void.__iter__cCsdSzl The native Python datatype representation of this value :return: None Nr)rUr)r)r*rx?s z Void.nativeFcCsdS)r|r+r)rIrr)r)r*rZJs z Void.dumpN)F) rrrrrGrrrrpropertyrxrZr)r)r)r*r#s  rcsZeZdZdZdZdddZeddZeddZdd d Z fd d Z dddZ Z S)Anyz A value class that can contain any value, and allows for easy parsing of the underlying encoded value using a spec. This is normally contained in a Structure that has an ObjectIdentifier field and _oid_pair and _oid_specs defined. Nc Kstj|f|z@|dk rLt|ts4ttdt|||jdf|_||_ WnVt tfk r}z4|j dd}|j ddt|f||_ |W5d}~XYnXdS)z Sets the value of the object before passing to Asn1Value.__init__() :param value: An Asn1Value object that will be set as the parsed value Nz` value must be an instance of Asn1Value, not %s r rr;) r&rOr0r1r r r<_parsedrZrGr?rH)rIr6r5rNrHr)r)r*rOgs z Any.__init__cCs|jdkr||jdjS)z The native Python datatype representation of this value :return: The .native value from the parsed value object Nr)rparserxrUr)r)r*rxs z Any.nativecCs|jdkr||jdSzw Returns the parsed object from .parse() :return: The object returned by .parse() NrrrrUr)r)r*rts z Any.parsedc Cs|jdks"|jdd||fkrz|p*i}t||jdk rdd|krZ|j|d|d<n |j|d<|j|j|j}t|||d\}}|||f|_d|_d|_d|_d|_||_d|_WnXt t fk r}z4|j dd}|j dd t |f||_ |W5d}~XYnX|jdS) v Parses the contents generically, or using a spec with optional params :param spec: A class derived from Asn1Value that defines what class_ and tag the value should have, and the semantics of the encoded value. The return value will be of this type. If omitted, the encoded value will be decoded using the standard universal tag based on the encoded tag number. :param spec_params: A dict of params to pass to the spec object :return: An object of the type spec, or if not present, a child of Asn1Value Nr rr9r.r/Fr+r while parsing %s) r_tag_type_to_explicit_implicitr9rrGrr3r2r:r?r1rHr ) rIr.r/Z passed_paramsrG parsed_valuer7rNrHr)r)r*rs4"     z Any.parsecs"tt|||||j|_dS)a Copies the contents of another Any object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects N)rrrarrorr)r*ras z Any._copyFcCs$|jdkr||jdj|dS)r|Nrr)rrrZrr)r)r*rZs zAny.dump)N)NN)F) rrrrrrOrrxrtrrarZrr)r)rr*r\s   2 rcseZdZdZdZdZdZdZdZdZ dZ e dddZ ddZ ddd Zed d Zejd d Zed dZddZeddZeddZddZddZfddZdddZZS) ChoicezF A class to handle when a value may be one of several options NFcKs2t|tstdt|t||||d\}}|S)a Loads a BER/DER-encoded byte string using the current class as the spec :param encoded_data: A byte string of BER or DER encoded data :param strict: A boolean indicating if trailing data should be forbidden - if so, a ValueError will be raised when trailing data exists :return: A instance of the current class r,r-)r0rr1r r3)r4r(r%r5r6r7r)r)r*r's z Choice.loadcCst|j}i|_i|_t|jD]R\}}t|dkrD|if}||j|<t|d|d}||j|<||j|d<qdS)zS Generates _id_map from _alternatives to allow validating contents rr!r rN)r<_id_map _name_map enumerate _alternativesrA_build_id_tuple)rIr4indexinfoid_r)r)r*r8+s    z Choice._setupc Kst|tj|f|z|ddk r4ttd|dk r$t|trt|dkrlttdt |t|t | d\}}t|t rt|dkrttdt |t||d}|d}||j krttd |t ||j ||_|j|j\}}}t||s||f|}n t||}||_WnXttfk r~}z4|jdd}|jdd t |f||_|W5d}~XYnXdS) aq Checks to ensure implicit tagging is not being used since it is incompatible with Choice, then forwards on to Asn1Value.__init__() :param name: The name of the alternative to be set - used with value. Alternatively this may be a dict with a single key being the name and the value being the value, or a two-element tuple of the name and the value. :param value: The alternative value to set - used with name :raises: ValueError - when implicit param is passed (or legacy tag_type param is "implicit") r:Nz The Choice type can not be implicitly tagged even if in an implicit module - due to its nature any tagging must be explicit r z When passing a dict as the "name" argument to %s, it must have a single key/value - however %d were present rr!z When passing a tuple as the "name" argument to %s, it must have two elements, the name and value - however %d were present z The name specified, "%s", is not a valid alternative for %s r;)rr&rOrjr?r r0rirAr listrtupler_choicer _fix_taggingrr1rH) rInamer6r5r7r.paramsrNrHr)r)r*rO;sR            zChoice.__init__cCs|jdk r|jjS|jS)zj :return: A byte string of the DER-encoded contents of the chosen alternative N)rrG _contentsrUr)r)r*rGs zChoice.contentscCs ||_dS)zo :param value: A byte string of the DER-encoded contents of the chosen alternative NrrIr6r)r)r*rGscCs|js|j|jd|_|jS)zc :return: A unicode string of the field name of the chosen alternative r)_namerrrUr)r)r*rsz Choice.namec Cs|jdkrz,|j|j\}}}t|j||d\|_}WnVttfk r}z4|jdd}|jddt|f||_|W5d}~XYnX|jS)z} Parses the detected alternative :return: An Asn1Value object of the chosen alternative Nrr rr) rrrr3rr?r1rHr )rIr7r.rrNrHr)r)r*rs z Choice.parsecCs|S)zT :return: An Asn1Value object of the chosen alternative )rrUr)r)r*rusz Choice.chosencCs|jjS)z The native Python datatype representation of this value :return: The .native value from the contained value object )rurxrUr)r)r*rxs z Choice.nativecs||f}jdk rXjd|kr2ttdtt|t|\\}}}}}}}||f}|jkrrj|_dSjdk rj dk rtj dkrttdt|jj fkrd_dS ||}fddjD}ttd |td |dS) a Ensures that the class and tag specified exist as an alternative :param class_: The integer class_ from the encoded value header :param tag: The integer tag from the encoded value header :param contents: A byte string of the contents of the value - used when the object is explicitly tagged :raises: ValueError - when value is not a valid alternative Nr}z %s was explicitly tagged, but the value provided does not match the class and tag r z| %s was implicitly tagged, but more than one alternative exists rcs g|]}|d|dqSr$)_format_class_tag).0pairrUr)r* sz#Choice.validate..zs Value %s did not match the class and tag of any of the alternatives in %s: %s , ) r9r?r r rrArrrDr2rrjoin)rIrDr2rGrr7Zasn1Zasn1sr)rUr*validates:    zChoice.validatecCsdt||fS)zo :return: A unicode string of a human-friendly representation of the class and tag z[%s %s])rBupper)rIrDr2r)r)r*rszChoice._format_class_tagcs2tt||||j|_|j|_||j|_dS)a Copies the contents of another Choice object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects N)rrrarrrrorr)r*ras z Choice._copycCs|jdk r |jdddkr d}|jj|d|_|jdks>|r|d|_|jdk r||jD]&\}}t|d||j|j|j|_qT|j|jS)r|Nr}r~Trr+r )rrurZrr9r)rIrrDr2r)r)r*rZ-s   z Choice.dump)F)NN)F)rrrrrrrrrrrrr'r8rOrrGsetterrrrurxrrrarZrr)r)rr*rs6   T     @ rc@seZdZdZdZdZed'ddZd(ddZdd Z d d Z d d Z ddZ ddZ ddZddZddZd)ddZd*ddZeddZdd Zd!d"Zd#d$Zd%d&ZdS)+Concata A class that contains two or more encoded child values concatentated together. THIS IS NOT PART OF THE ASN.1 SPECIFICATION! This exists to handle the x509.TrustedCertificate() class for OpenSSL certificates containing extra information. NFcCs |||dS)a Loads a BER/DER-encoded byte string using the current class as the spec :param encoded_data: A byte string of BER or DER encoded data :param strict: A boolean indicating if trailing data should be forbidden - if so, a ValueError will be raised when trailing data exists :return: A Concat object )rGr%r))r4r(r%r)r)r*r'Ssz Concat.loadc Cs|dk rzpt|}g|_d}|jD]2}||krBt|||d\}}n|}|j|q"|rv||krv||}td|WnVttfk r} z4| jdd} | jddt|f| | _| W5d} ~ XYnX|dk r|jdkrdgt|j|_t |D]\} } | | | qdS)a :param value: A native Python datatype to initialize the object value with :param contents: A byte string of the encoded contents of the value :param strict: A boolean indicating if trailing data should be forbidden - if so, a ValueError will be raised when trailing data exists in contents :raises: ValueError - when an error occurs with one of the children TypeError - when an error occurs with one of the children Nr)rr.4Extra data - %d bytes of trailing data were providedr r;) rA _children _child_specsr3appendr?r1rHr r __setitem__) rIr6rGr%roffsetr.Z child_value extra_bytesrNrHrdatar)r)r*rOes,    zConcat.__init__cCstr |S|SdSrPrQrUr)r)r*rVs zConcat.__str__cCs|S)z; A byte string of the DER-encoded contents rZrUr)r)r*rSszConcat.__bytes__cCst|SrW)r@rUr)r)r*rTszConcat.__unicode__cCsdt|t|t|fS)rWrX)r rYr@rZrUr)r)r*r[szConcat.__repr__cCs|}||tj|S)z| Implements the copy.copy() interface :return: A new shallow copy of the Concat object )r<rarbr^r)r)r*rcszConcat.__copy__cCs&|}||t|<||tj|S)z Implements the copy.deepcopy() interface :param memo: A dict for memoization :return: A new deep copy of the Concat object and all child objects )r<rYrarbrdrer)r)r*rgs  zConcat.__deepcopy__cCs t|S)zQ Copies the object :return: A Concat object rhrUr)r)r*rbsz Concat.copycCs4|j|jkr$ttdt|t|||j|_dS)a Copies the contents of another Concat object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects rmN)r<r1r r rror)r)r*ras z Concat._copyr cCsNd|}td|t|t|ftd|f|jD]}||dq6dS)rrrs%s%s Object #%sz %s Children:r!N)ryr rYrrwrIrzr{childr)r)r*rws  z Concat.debugcCs$d}|jD]}||j|d7}q |S)r|r+r)rrZrIrrGrr)r)r*rZs  z Concat.dumpcCs|S)z` :return: A byte string of the DER-encoded contents of the children rrUr)r)r*rGszConcat.contentscCs t|jS). :return: Integer )rArrUr)r)r*rszConcat.__len__cCs8|t|jdks|dkr.ttd|t||j|S)z Allows accessing children by index :param key: An integer of the child index :raises: KeyError - when an index is invalid :return: The Asn1Value object of the child specified r rzN No child is definition for position %d of %s )rArKeyErrorr r rrIrr)r)r* __getitem__!szConcat.__getitem__cCsZ|t|jdks|dkr.ttd|t|t|tsLttd|t|||j|<dS)aG Allows settings children by index :param key: An integer of the child index :param value: An Asn1Value object to set the child to :raises: KeyError - when an index is invalid ValueError - when the value is not an instance of Asn1Value r rzK No child is defined for position %d of %s zz Value for child %s of %s is not an instance of asn1crypto.core.Asn1Value N) rArrr r r0r&r?r)rIrr6r)r)r*r:s  zConcat.__setitem__cCs t|jS)zB :return: An iterator of child values )rrrUr)r)r*r^szConcat.__iter__)F)NNF)r )F)rrrrrrrr'rOrVrSrTr[rcrgrbrarwrZrrGrrrrr)r)r)r*rFs,  -    $rc@sDeZdZdZdZdZdddZddZdd d Zd d Z d dZ dS) PrimitivezO Sets the class_ and method attributes for primitive, universal values rNc Kstj|f|z:|dk r ||_n&|dk r4||n|dk rF||WnVttfk r}z4|jdd}|jddt|f||_|W5d}~XYnXdS)a^ Sets the value of the object before passing to Asn1Value.__init__() :param value: A native Python datatype to initialize the object value with :param default: The default value if no value is specified :param contents: A byte string of the encoded contents of the value Nr rr;)r&rOrGrEr?r1rHr )rIr6rMrGr5rNrHr)r)r*rOps zPrimitive.__init__cCsHt|ts"ttdt|t|||_||_d|_|jdkrDd|_dS)_ Sets the value of the object :param value: A byte string H %s value must be a byte string, not %s Nr+) r0rr1r r rnrGrrrr)r)r*rEs  z Primitive.setFcCsD|jdk r |jdddkr d}|r:|j}d|_||t|S)r|Nr}r~T)rrxrGrEr&rZrIrrxr)r)r*rZs  zPrimitive.dumpcCs ||k S)Nr)rr)r)r*__ne__szPrimitive.__ne__cCst|tsdS|j|jkrdS|jj|jjkr2dS|j|jkrN|j|jkrNdSt|jjt|jgBttttg}t|jjt|jgBttttg}||Br|j|jkS|j s|j s|j s|j r| | kS| | kS)rFT) r0rrGr<r2rE __bases__r&rr:r9rlrZ)rIrpZ self_bases other_basesr)r)r*rs  && zPrimitive.__eq__)NNN)F) rrrrrDrFrOrErZrrr)r)r)r*rgs  rcsDeZdZdZdZdZddZddZfdd Ze d d Z Z S) AbstractStringz A base class for all strings that have a known encoding. In general, we do not worry ourselves with confirming that the decoded values match a specific set of characters, only that they are decoded into a Python unicode string latin1NcCsbt|ts"ttdt|t|||_||j|_d|_ |j rNd|_ d|_ |j dkr^d|_ dS)zb Sets the value of the string :param value: A unicode string K %s value must be a unicode string, not %s NFrr+) r0rr1r r _unicoder] _encodingrGrrrFrrr)r)r*rEs  zAbstractString.setcCs0|jdkrdS|jdkr*||j|_|jS)rWN)rGrrdecoderrUr)r)r*rT s   zAbstractString.__unicode__cstt||||j|_dS)a& Copies the contents of another AbstractString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects N)rrrarrorr)r*ras zAbstractString._copycCs|jdkrdS|Sz The native Python datatype representation of this value :return: A unicode string or None N)rGrTrUr)r)r*rx(s zAbstractString.native) rrrrrrrErTrarrxrr)r)rr*rs rc@s8eZdZdZdZddZddZddZed d Z d S) Booleanz7 Represents a boolean in both ASN.1 and Python r cCs2t||_|sdnd|_d|_|jdkr.d|_dS)z Sets the value of the object :param value: True, False or another value that works with bool() Nr+)boolrnrGrrrr)r)r*rE>s   z Boolean.setcCs|S)4 :return: True or False )__bool__rUr)r)r*rMszBoolean.__nonzero__cCs |jdkS)rrrrUr)r)r*rTszBoolean.__bool__cCs(|jdkrdS|jdkr"||_|jS)z{ The native Python datatype representation of this value :return: True, False or None N)rGrnrrUr)r)r*rx[s   zBoolean.nativeN) rrrrr2rErrrrxr)r)r)r*r7src@s0eZdZdZdZddZddZeddZd S) Integerz8 Represents an integer in both ASN.1 and Python r!cCst|trP|jdkr&ttdt|||jkrDttdt|||j|}n"t|tsrttdt|t||jr||jkr|j|n||_ t |dd|_ d|_ |j dkrd|_ dS)z Sets the value of the object :param value: An integer, or a unicode string if _map is set :raises: ValueError - when an invalid value is passed Nz\ %s value is a unicode string, but no _map provided zR %s value, %s, is not present in the _map z %s value must be an integer or unicode string when a name_map is provided, not %s Tsignedr+)r0rrr?r r rrr1rnrrGrrrr)r)r*rEss0       z Integer.setcCst|jddS)1 :return: An integer Tr)rrGrUr)r)r*__int__szInteger.__int__cCsL|jdkrdS|jdkrF||_|jdk rF|j|jkrF|j|j|_|jSzz The native Python datatype representation of this value :return: An integer or None N)rGrnrrrUr)r)r*rxs   zInteger.nativeN) rrrrr2rErrrxr)r)r)r*rls 0rcs@eZdZdZdZddZddZfddZed d Z Z S) _IntegerBitStringzY A mixin for IntegerBitString and BitString to parse the contents as an integer. r)cCs|jr gStrt|jdn|jd}t|jdd}t|jdd}|sZ||dfgSt|jdkrvtd||dkrtd|t|d|>d@|}||L}||8}|||fgS) a Parse the contents of a primitive BitString encoding as an integer value. Allows reconstructing indefinite length values. :raises: ValueError - when an invalid value is passed :return: A list with one tuple (value, bits, unused_bits) where value is an integer with the value of the BitString, bits is the bit count of value and unused_bits is a tuple of 1s and 0s. rr Nr)$Empty bit string has {0} unused bitsBit string has {0} unused bits) rrRordrGrrAr?format_int_to_bit_tuple)rIunused_bits_lenr6bits unused_bitsr)r)r*rs z_IntegerBitString._as_chunkcCs`|js|dSd}d}d}|D].\}}}|d@r@td||7}||>|B}q&|||fS)aa Combines the chunks into a single value. :raises: ValueError - when an invalid value is passed :return: A tuple (value, bits, unused_bits) where value is an integer with the value of the BitString, bits is the bit count of value and unused_bits is a tuple of 1s and 0s. rr)r4Only last chunk in a bit string may have unused bits)rrrr?)rIr6Z total_bitsr chunkrr)r)r*_chunks_to_ints  z _IntegerBitString._chunks_to_intcstt||||j|_dS)a) Copies the contents of another _IntegerBitString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects N)rrra _unused_bitsrorr)r*ra s z_IntegerBitString._copycCs |j|jSzp The unused bits of the bit string encoding. :return: A tuple of 1s and 0s rxr rUr)r)r*r s z_IntegerBitString.unused_bits) rrrrr rr rarr rr)r)rr*rs' rc@sDeZdZdZdZdZddZddZdd Zd d Z e d d Z dS) BitStringzK Represents a bit string from ASN.1 as a Python tuple of 1s and 0s rNcCs2t||j}|jdk r.t|jd|_dS)rNr )rr8r<rmaxkeys_size)rIr4r)r)r*r82s  zBitString._setupc Cst|tr|jdkr&ttdt|dg|j}||_td|jD]*}|j |}|dkr^qD||krDd||<qDd t t |}n~|j tkr|jdkr||_n8t|_t|D]&\}}|r|j ||}|j|qd t t |}nttdt|t||jdk rBt||jkr8ttdt||jt||d}t|}|d }d} |dkrtd |} |d| 7}tt|d } | rt| } nd } |dkrd } ntt|d } t| | krd | t| | } | | |_d | |_d|_|jrd|_d|_|jd krd |_dS)z Sets the value of the object :param value: An integer or a tuple of integers 0 and 1 :raises: ValueError - when an invalid value is passed NF %s._map has not been defined rr rz %s value must be a tuple of ones and zeros or a set of unicode strings, not %s zf %s value must be at most %s bits long, specified was %s long 0rrr+r!rF)r0rErr?r r rrnrangerjrmaprr<rraddr1rArstripintmathceilrrGr rrrFr) rIr6rrrbitrsizeZsize_modZ extra_bitsZ size_in_bytesZextra_bits_byteZ value_bytesr)r)r*rE=sz                z BitString.setcCst|t}|sJt|jts,ttdt|||jkrJttdt|||jdkrZ|j |jdkrt |j|dkrt |j|SdS|r|j ||}||jkS)aG Retrieves a boolean version of one of the bits based on a name from the _map :param key: The unicode string of one of the bit names :raises: ValueError - when _map is not set or the key name is invalid :return: A boolean if the bit is set rT %s._map does not contain an entry for "%s" Nr F) r0rrrir?r r rrnrxrArrj)rIris_intr)r)r*rs,     zBitString.__getitem__cCst|t}|sH|jdkr*ttdt|||jkrHttdt|||jdkrX|j|jdkrt |j}t |d}||kr| dg|||rdnd||<t ||_nD|r|j ||}|r||jkr|j|n||jkr|j|||jdS)a Sets one of the bits based on a name from the _map :param key: The unicode string of one of the bit names :param value: A boolean value :raises: ValueError - when _map is not set or the key name is invalid Nrr r r)r0rrr?r r rrnrxrrAextendrrjrremoverE)rIrr6r!Z new_nativeZmax_keyr)r)r*rs<           zBitString.__setitem__cCs|jdkr,|jdkr |dn |t|jdkr|\}}|_t||}|jrt|_t|D]&\}}|rf|j||}|j |qfn||_|jS)z The native Python datatype representation of this value :return: If a _map is set, a set of names, or if no _map is set, a tuple of integers 1 and 0. None if no value. Nr)) rGrrErnr r rrrjr)rIZ int_valueZ bit_countrrrrr)r)r*rx s      zBitString.native) rrrrr2rr8rErrrrxr)r)r)r*r)s c/9rcs\eZdZdZdZdZdZddZddZfd d Z d d Z e d dZ e ddZ ZS)OctetBitStringzB Represents a bit string in ASN.1 as a Python byte string rNr)cCsdt|ts"ttdt|t|||_d||_d|_d|_|j rPd|_ d|_ |j dkr`d|_ dS) Sets the value of the object :param value: A byte string :raises: ValueError - when an invalid value is passed rrr)NFrr+) r0rr1r r _bytesrGr rrrFrrr)r)r*rE5 s   zOctetBitString.setcCs|jdkrdS|jdkrz|js4|d\|_|_nF|}d|_|D]}|jrXtd|d|_qFddd|D|_|jS) 4 :return: A byte string Nr+rr)r r css|]}|dVqdS)rNr))rr r)r)r* g sz+OctetBitString.__bytes__..)rGr&rrr rr?r)rIchunksr r)r)r*rST s   zOctetBitString.__bytes__cs&tt||||j|_|j|_dS)a& Copies the contents of another OctetBitString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects N)rr$rar&r rorr)r*rak s zOctetBitString._copycCstrt|jdn|jd}|s4|jdddfgSt|jdkrPtd||dkrftd|d|>d}trt|jdn|jd}||@}|jddtrt|nt|f}t||@|}||fgS) z Allows reconstructing indefinite length values :raises: ValueError - when an invalid value is passed :return: List with one tuple, consisting of a byte string and an integer (unused bits) rr Nr)rrrr}) rRrrGrAr?rchrbytesr)rIrmaskZ last_byteZ zeroed_byter6r r)r)r*r{ s   $zOctetBitString._as_chunkcCs|jdkrdS|S} The native Python datatype representation of this value :return: A byte string or None NrGrSrUr)r)r*rx s zOctetBitString.nativecCs |j|jSrrrUr)r)r*r  s zOctetBitString.unused_bits)rrrrr2r&r rErSrarrrxr rr)r)rr*r$( s " r$c@s(eZdZdZdZddZeddZdS)IntegerBitStringz> Represents a bit string in ASN.1 as a Python integer rcCst|ts"ttdt|t||dkr>ttdt||||_dt|dd|_d|_ d|_ |j rtd |_ d|_ |j d krd |_ dS) Sets the value of the object :param value: An integer :raises: ValueError - when an invalid value is passed M %s value must be a positive integer, not %s rM %s value must be a positive integer, not %d rTrr)NFr+)r0rr1r r r?rnrrGr rrrFrrr)r)r*rE s*  zIntegerBitString.setcCs0|jdkrdS|jdkr*|\|_}|_|jSr)rGrnr r )rI__r)r)r*rx s  zIntegerBitString.nativeNrrrrr2rErrxr)r)r)r*r0 s (r0csDeZdZdZdZdZddZddZfdd Ze d d Z Z S) OctetStringz; Represents a byte string in both ASN.1 and Python NcCsZt|ts"ttdt|t|||_||_d|_|jrFd|_d|_ |j dkrVd|_ dSrrNFrr+ r0rr1r r r&rGrrrFrrr)r)r*rE s  zOctetString.setcCs(|jdkrdS|jdkr"||_|jSr'Nr+rGr&rrUr)r)r*rS s    zOctetString.__bytes__cstt||||j|_dS)a# Copies the contents of another OctetString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects N)rr6rar&rorr)r*ra+ s zOctetString._copycCs|jdkrdS|Sr-r/rUr)r)r*rx: s zOctetString.native) rrrrr2r&rErSrarrxrr)r)rr*r6 s r6c@s4eZdZdZdZdZddZeddZdd Z dS) IntegerOctetStringz? Represents a byte string in ASN.1 as a Python integer r7NcCst|ts"ttdt|t||dkr>ttdt||||_t|d|jd|_ d|_ |j rnd|_ d|_ |j dkr~d|_ dS)r1r2rr3F)rwidthNr+)r0rr1r r r?rnr_encoded_widthrGrrrFrrr)r)r*rEV s(  zIntegerOctetString.setcCs,|jdkrdS|jdkr&t||_|jSr)rGrnrrrUr)r)r*rx| s  zIntegerOctetString.nativecCs.||_|jdk r*t|j|kr*||jdS)z Set the explicit enoding width for the integer :param width: An integer byte width to encode the integer to N)r>rGrArErx)rIr=r)r)r*set_encoded_width sz$IntegerOctetString.set_encoded_width) rrrrr2r>rErrxr?r)r)r)r*r<I s& r<csveZdZdZdZdZdddZddZdddZd d Z d d Z fd dZ e ddZ e ddZdddZZS)ParsableOctetStringr7NcKsVd}|dkr*|dk r*t|tr*|}d}tj|fd|i||rR||jdf|_dS)a Allows providing a parsed object that will be serialized to get the byte string value :param value: A native Python datatype to initialize the object value with :param parsed: If value is None and this is an Asn1Value object, this will be set as the parsed value, and the value will be obtained by calling .dump() on this object. FNTr6)r0r&rZrrOr<r)rIr6rtr5Z set_parsedr)r)r*rO szParsableOctetString.__init__cCsZt|ts"ttdt|t|||_||_d|_|jrFd|_d|_ |j dkrVd|_ dSr8r9rr)r)r*rE s  zParsableOctetString.setcCsL|jdks |jdd||fkrBt|||d\}}|||f|_|jdS)rNr rrr)rr3rS)rIr.r/rr7r)r)r*r s  zParsableOctetString.parsecCs(|jdkrdS|jdkr"||_|jSr:r;rUr)r)r*rS s    zParsableOctetString.__bytes__cCs|S)z Returns a byte string that can be passed into .set() :return: A python value that is valid to pass to .set() )rSrUr)r)r*r sz#ParsableOctetString._setable_nativecs*tt||||j|_||j|_dS)a+ Copies the contents of another ParsableOctetString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects N)rr@rar&rrorr)r*ra s zParsableOctetString._copycCs0|jdkrdS|jdk r$|jdjS|SdS)r.Nr)rGrrxrSrUr)r)r*rx s   zParsableOctetString.nativecCs|jdkr||jdSrrrUr)r)r*rt# s zParsableOctetString.parsedFcCsH|jr d}|r>|jdk r(|jj|d}n|j}d|_||t|S)r|TNr)rrrtrZrxrGrEr&rr)r)r*rZ1 s   zParsableOctetString.dump)NN)NN)F)rrrr2rr&rOrErrSrrarrxrtrZrr)r)rr*r@ s      r@c@s eZdZdZddZddZdS)ParsableOctetBitStringrcCs^t|ts"ttdt|t|||_d||_d|_|jrJd|_d|_ |j dkrZd|_ dS)r%rrNFrr+r9rr)r)r*rEP s   zParsableOctetBitString.setcCs6trt|jdn|jd}|r(td|jddS)z Allows reconstructing indefinite length values :raises: ValueError - when an invalid value is passed :return: A byte string rz1ParsableOctetBitString should have no unused bitsr N)rRrrGr?)rIrr)r)r*rn s z ParsableOctetBitString._as_chunkN)rrrr2rErr)r)r)r*rAL srAc@s,eZdZdZdZdZddZeddZdS) Nullz< Represents a null value in ASN.1 as None in Python r+cCs d|_dS)zV Sets the value of the object :param value: None r+Nrrr)r)r*rE szNull.setcCsdSrr)rUr)r)r*rx s z Null.nativeN) rrrrr2rGrErrxr)r)r)r*rB s  rBc@sXeZdZdZdZdZeddZeddZdd Z d d Z e d d Z e ddZ dS)ObjectIdentifier` Represents an object identifier in ASN.1 as a Python unicode dotted integer string NcCsF|jdkrttdt|t|ts8ttdt||j||S)a^ Converts a dotted unicode string OID into a mapped unicode string :param value: A dotted unicode string OID :raises: ValueError - when no _map dict has been defined on the class TypeError - when value is not a unicode string :return: A mapped unicode string N> %s._map has not been defined H value must be a unicode string, not %s )rr?r r r0rr1rjr4r6r)r)r*r s  zObjectIdentifier.mapcCs|tkr|dt|<|jdkr6ttdt|t|tsRttdt|||j krf|j |St |sttdt|||S)a Converts a mapped unicode string value into a dotted unicode string OID :param value: A mapped unicode string OR dotted unicode string OID :raises: ValueError - when no _map dict has been defined on the class or the value can't be unmapped TypeError - when value is not a unicode string :return: A dotted unicode string OID TNrGrHzL %s._map does not contain an entry for "%s" ) r=r8rr?r r r0rr1r_OID_REmatchrIr)r)r*unmap s,      zObjectIdentifier.unmapcCs8t|ts"ttdt|t|||_|jdk rF||jkrF|j|}d|_d}t | dD]\}}t |}|dkr~|}q^nR|dkr|dkrt tdt |n"|dkr|d krt td t ||d |}td |@}|d ?}|dkr td d |@B|}|d ?}q|j|7_q^d|_|jdkr4d|_dS)a  Sets the value of the object :param value: A unicode string. May be a dotted integer string, or if _map is provided, one of the mapped values. :raises: ValueError - when an invalid value is passed rNr+.rr r!z\ First arc must be one of 0, 1 or 2, not %s (z Second arc must be less than 40 if first arc is 0 or 1, not %s r)r0rr1r r rnrrrGrsplitrr?r@rrr)rIr6firstrpartZ encoded_partr)r)r*rE sL         zObjectIdentifier.setcCs|jSr)dottedrUr)r)r*rT? szObjectIdentifier.__unicode__cCs|jdkrg}d}|jD]}tr(t|}|d}||d@7}|d@dkrt|dkr|dkr~|td|t|dq|dkr|td|t|dq|td|t|n|t|d}qd ||_|jS) z :return: A unicode string of the object identifier in dotted notation, thus ignoring any mapped value NrrPrOPr!rNr rM)_dottedrGrRrrArrr)rIrrSbyter)r)r*rTG s,      zObjectIdentifier.dottedcCsJ|jdkrdS|jdkr |j|_|jdk rD|j|jkrD|j|j|_|jS)aC The native Python datatype representation of this value :return: A unicode string or None. If _map is not defined, the unicode string is a string of dotted integers. If _map is defined and the dotted string is present in the _map, the mapped value is returned. N)rGrnrTrrUr)r)r*rxk s  zObjectIdentifier.native)rrrrr2rVrrrLrErTrrTrxr)r)r)r*rD s ! 1A #rDc@seZdZdZdZdS)ObjectDescriptorzO Represents an object descriptor from ASN.1 - no Python implementation rNrrrrr2r)r)r)r*rX srXc@seZdZdZdZdS) InstanceOfzF Represents an instance from ASN.1 - no Python implementation rNrYr)r)r)r*rZ srZc@seZdZdZdZdS)RealzH Represents a real number from ASN.1 - no Python implementation NrYr)r)r)r*r[ sr[c@s(eZdZdZdZddZeddZdS) Enumeratedz\ Represents a enumerated list of integers from ASN.1 as a Python unicode string cCst|ts,t|ts,ttdt|t|t|tr`||jkrTttdt|||j|}n||jkr~ttdt||t ||dS)z Sets the value of the object :param value: An integer or a unicode string from _map :raises: ValueError - when an invalid value is passed zY %s value must be an integer or a unicode string, not %s zL %s value "%s" is not a valid value zB %s value %s is not a valid value N) r0rrr1r r rr?rrrErr)r)r*rE s*     zEnumerated.setcCs.|jdkrdS|jdkr(|j||_|jSr)rGrnrrrUr)r)r*rx s  zEnumerated.nativeNr5r)r)r)r*r] s +r]c@seZdZdZdZdZdS) UTF8StringzI Represents a UTF-8 string from ASN.1 as a Python unicode string r\Nrrrrr2rr)r)r)r*r_ sr_c@seZdZdZdZdS) RelativeOidrE NrYr)r)r)r*rb srbcseZdZdZdZdZdZdZdZdZ gZ dZ dZ dZ dZdZdZdZd.ddZed d Zejd d Zd d ZddZddZddZddZddZddZd/ddZddZddZd d!Z d0d"d#Z!d$d%Z"ed&d'Z#fd(d)Z$d1d*d+Z%d2d,d-Z&Z'S)3Sequencezf Represents a sequence of fields from ASN.1 as a Python object with a dict-like interface rr NFc Kstj|f|d}|dkrL|dk rLd}|jdkrH|jdkr@d}n||}|dk r~z|jr|dd|jD}t|}n|}t|}|D]d}|r|j|}|t |jkr|j|t k r||kr| |q||kr| |||| |qt |r"t tdt|dtt|WnXt tfk r|} z4| jdd} | jd d t|f| | _| W5d} ~ XYnXdS) a" Allows setting field values before passing everything else along to Asn1Value.__init__() :param value: A native Python datatype to initialize the object value with :param default: The default value if no value is specified FNTcSsg|] }|dqSrr))rrr)r)r*rE sz%Sequence.__init__..z One or more unknown fields was passed to the constructor of %s: %s rr rr;)r&rOchildrenrG_parse_children_fieldsrEr _field_maprAVOIDr#rr?r r rsortedrr1rH) rIr6rMr5Zcheck_existingrZ unused_keysrrrNrHr)r)r*rO' sH         zSequence.__init__cCs&|jdkr|jS|r ||jSz` :return: A byte string of the DER-encoded contents of the sequence Nrfr _is_mutated _set_contentsrUr)r)r*rGh s  zSequence.contentscCs ||_dSze :param value: A byte string of the DER-encoded contents of the sequence Nrrr)r)r*rGw scCs@|j}|jdk r<|jD]$}t|ts.t|tr|p8|}q|Sz~ :return: A boolean - if the sequence or any children (recursively) have been mutated N_mutatedrfr0rd SequenceOfrnrIZmutatedrr)r)r*rn s   zSequence._is_mutatedcCs*|j|}|jtkr&t|}|j|<|Sz] Builds a child object if the child has only been parsed into a tuple so far rfr<r_buildrIrrr)r)r* _lazy_child s  zSequence._lazy_childcCs|jdkr|t|jS)rNrfrgrArUr)r)r*r s zSequence.__len__c Cs|jdkr|t|tsD||jkr:ttd|t||j|}|t|jkrfttd|t|z | |WSt t fk r}z4|j dd}|j ddt|f||_ |W5d}~XYnXdS)a9 Allows accessing fields by name or index :param key: A unicode string of the field name, or an integer of the field index :raises: KeyError - when a field name or index is invalid :return: The Asn1Value object of the field specified NL No field named "%s" defined for %s zL No field numbered %s is present in this %s r rr) rfrgr0rrirr r rArzr?r1rH)rIrrNrHr)r)r*r s,     zSequence.__getitem__c Cs|jdkr|t|tsD||jkr:ttd|t||j|}||\}}}}}| |||||}d} t|t r|j dk} n |j dk} | rt td|t|||j|<|jdk r|j|j|j|j|d<d|_dS)a Allows settings fields by name or index :param key: A unicode string of the field name, or an integer of the field index :param value: A native Python datatype to set the field value to. This method will construct the appropriate Asn1Value object from _fields. :raises: ValueError - when a field name or index is invalid Nr|FzG Value for field "%s" of %s is not set rT)rfrgr0rrirr r _determine_spec _make_valuerrtrGr?rnrxrhrs) rIrr6 field_name field_spec value_spec field_paramsr7 new_valueZ invalid_valuer)r)r*r s4         zSequence.__setitem__cCs|jdkr|t|tsD||jkr:ttd|t||j|}|j|\}}}|rhd|kr|d|kr|t td|t|d|krt |j|<|j dk rd|j |<n | |dd|_ dS)a/ Allows deleting optional or default fields by name or index :param key: A unicode string of the field name, or an integer of the field index :raises: ValueError - when a field name or index is invalid, or the field is not optional or defaulted Nr|rMrLz Can not delete the value for the field "%s" of %s since it is not optional or defaulted T)rfrgr0rrirr r rhr?rjrnrrs)rIrrr7rr)r)r* __delitem__ s.         zSequence.__delitem__ccs|jD]}|dVqdS)zE :return: An iterator of field key names rN)rh)rIrr)r)r*r6s zSequence.__iter__cCs|jdkr|t}t|jD]\}}|j|}|dkrBd}nH|jtkr~|rd||j|d}q|d|d|d}n |j|d}|drd|dkr|d f|d}||krq"| |q"| |_ d|_ |j dkrd|_ dS) a Updates the .contents attribute of the value with the encoded value of all of the child objects :param force: Ensure all contents are in DER format instead of possibly using cached BER-encoded data Nr+rrr7rCr!rMr )rfrgrrrhr<rrzrZwritegetvaluerrr)rIrrGrrrZ child_dump default_valuer)r)r*ro?s*        zSequence._set_contentscCs$|j}i|_g|_g|_t|jD]P\}}t|dkrJ|if}||j|<||j|d<|jt|d|dq"|j dk r|j|j d|j|j df|_ t|jD]t\}}|j dk o|d|j k}|j dk o|j d|k}|s|r|jdq|j|d|d|d|ddfqdSzS Generates _field_map, _field_ids and _oid_nums for use in parsing rrr!r N) r<ri _field_ids_precomputed_specsrrhrArr _oid_pair _oid_nums_spec_callbacksrIr4rfieldZ has_callbackZ is_mapped_oidr)r)r*r8ds$    "zSequence._setupc Cs|j|\}}}|}d}|jdk r||jkr|j|}||}|r|jtkrrt|dkrr|\}}|dkr|}d}q|dkr|}|}d}q|}nB|jdk r|jd|kr||jdj}||jkr|j|}|}|||||fS)a Determine how a value for a field should be constructed :param index: The field number :return: A tuple containing the following elements: - unicode string of the field name - Asn1Value class of the field spec - Asn1Value class of the value spec - None or dict of params to pass to the field spec - None or Asn1Value class indicating the value spec was derived from an OID or a spec callback Nr!r r) rhrr<rrArrzrx _oid_specs) rIrrrrr spec_overridecallbackoidr)r)r*r}s.   zSequence._determine_specc Cs|dkrd|krtS||k}t|t}t|trt|t}t|toNt|dk} t|todt|dk} |s| s| st t d|t || s| r||}t||s|} | |j |j|j|| _| } n|} nt||r|} |r| |n|r|r@t||s@|r |r2t|tr2tt d|t |t |||f|} ntt||rR|} n.t|trxtt d|t |t |||} |r|s|fd| i|} | | jdf| _| } t| |} | S) a& Contructs an appropriate Asn1Value object for a field :param field_name: A unicode string of the field name :param field_spec: An Asn1Value class that is the field spec :param value_spec: An Asn1Value class that is the vaue spec :param field_params: None or a dict of params for the field spec :param value: The value to construct an Asn1Value object from :return: An instance of a child class of Asn1Value NrLr!r z Can not set a native python value to %s, which has the choice type of %s - value must be an instance of Asn1Value zE %s value must be %s, not %s zM %s value must be %s, not %s r6)rj issubclassrrr0r&rrArir?r r rrDr2rGrrr1rZr<r) rIrrrrr6Zspecs_differentZis_anyZ is_asn1valueZis_tupleZis_dictwrapperrr)r)r*r~sf           zSequence._make_valuec Cs2|j}|jdkr|jrtgt|j|_t|jD]b\}\}}}d|kr2|j|rh|j|\}}}} }n||\}}}} }| |||| d|j|<q2dSz2g|_t|j} d} d} t|j} d}| | k}|rX|dkrt |j| | d\}} | | k}| | kr:|j| p|| \}}}} }| rd| ks:d| kr|j | |d|dfkr|t krd}t |trz,|f| }||d|d|dd }Wntk rYnX|sd| kr|jtn|j|f| | d 7} d }q|dks|rt |t r|}d}|r,||| |f}n ||| f}n| dkr| d | krg}| d }|dkr|j|}t|d krqd|dksd|dkr||d|d 8}q^t|d krd nd }d|}ttd| d t|dt|d |d||n|}|r>t|}t|ttfr>|jd d|j|| d 7} d}qt|j}|| kr|j|\}}} d| kr|j|f| n&d| kr|jtnttd||d 7}qbWn^ttfk r,}z:d|_|jd d}|jddt|f||_|W5d}~XYnXdS)Q Parses the contents and generates Asn1Value objects based on the definitions from _fields. :param recurse: If child objects that are Sequence or SequenceOf objects should be recursively parsed :raises: ValueError - when an error occurs parsing child objects NrMrrrLr!Fr7Tr rsrrz Data for field %s (%s class, %s method, tag %s) does not match the field definition%s of %s recursezV Field "%s" is missing from structure r)r<rrhrjrArfrrr}r~rrrrrrr?rrr rBrjMETHOD_NUM_TO_NAME_MAPrxr0rdrtrgr1rHr )rIrr4rr7rrrrrcontents_length child_pointerrZ field_lenpartsZagainrZ choice_matchtesterrZ missed_fieldsZ prev_fieldZprev_field_infopluralZmissed_field_namesrrNrHr)r)r*rgs       &               zSequence._parse_childrencCsZt|tsttdt||jdkr>ttdt|t||j|}| |}|dS)a Determines the spec to use for the field specified. Depending on how the spec is determined (_oid_pair or _spec_callbacks), it may be necessary to set preceding field values before calling this. Usually specs, if dynamic, are controlled by a preceding ObjectIdentifier field. :param field_name: A unicode string of the field name to get the spec for :return: A child class of asn1crypto.core.Asn1Value that the field must be encoded using zM field_name must be a unicode string, not %s Nz Unable to retrieve spec for field %s in the class %s because _fields has not been set r!) r0rr1r r rhr?r@rir})rIrrrr)r)r*r.s    z Sequence.specc Cs|jdkrdS|jdkr|jdkr0|jddzxt|_t|jD]`\}}|jtkrht|}||j|<z|j |d}Wnt k rt |}YnX|j |j|<qDWn^t tfk r}z:d|_|jdd}|jddt|f||_|W5d}~XYnX|jS)z The native Python datatype representation of this value :return: An OrderedDict or None. If an OrderedDict, all child values are recursively converted to native representation also. NTrrr r)rGrnrfrgr rr<rrxrh IndexErrorrrxr?r1rHr )rIrrrrNrHr)r)r*rxs,      zSequence.nativecsZtt||||jdk rVg|_|jD],}|jtkrD|j|q(|j|q(dS)a  Copies the contents of another Sequence object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects N)rrdrarfr<rrrbrIrprqrrr)r*ras    zSequence._copycCsh|jdkr|d|}t|||D]:}||j|}|tk r(td||f||dq(dS)rrNrsz%s Field "%s"r)rfrgrvrzrirjryrw)rIrzr{rrr)r)r*rws  zSequence.debugcCs|jdk r |jdddkr d}|r0|j|d|jr|jdk rt|jD]>\}\}}}|j|tk rhqJd|ksJd|krzqJttd|qJt |S) r|Nr}r~TrrMrLzN Field "%s" is missing from structure ) rrorhrfrrjr?r r&rZ)rIrrrr7rr)r)r*rZs  z Sequence.dump)NN)F)F)r )F)(rrrrr2rDrFrfrrsrhrrirrrrrrOrrGrrnrzrrrrrror8r}r~rgr.rxrarwrZrr)r)rr*rd sN  A    .7- %/`  ' !  rdcseZdZdZdZdZdZdZdZdZ dZ d.ddZ e d d Z e jd d Z d d ZddZddZddZddZddZddZddZddZddZd/d d!Zd0d"d#Zd$d%Ze d&d'Zfd(d)Zd1d*d+Zd2d,d-ZZ S)3rtz Represents a sequence (ordered) of a single type of values from ASN.1 as a Python object with a list-like interface rerr NFc Ks|r ||_tj|f|z`|dk r*||_nL|dkr>|dk r>|}|dk rvt|D]\}}|||qN|jdkrv|WnVttfk r}z4|j dd} |j ddt |f| |_ |W5d}~XYnXdS)a Allows setting child objects and the _child_spec via the spec parameter before passing everything else along to Asn1Value.__init__() :param value: A native Python datatype to initialize the object value with :param default: The default value if no value is specified :param contents: A byte string of the encoded contents of the value :param spec: A class derived from Asn1Value to use to parse children Nr rr;) _child_specr&rOrGrrror?r1rHr ) rIr6rMrGr.r5rrrNrHr)r)r*rO?s"  zSequenceOf.__init__cCs&|jdkr|jS|r ||jSrlrmrUr)r)r*rGjs  zSequenceOf.contentscCs ||_dSrprrr)r)r*rGyscCs@|j}|jdk r<|jD]$}t|ts.t|tr|p8|}q|Srqrrrur)r)r*rns   zSequenceOf._is_mutatedcCs*|j|}|jtkr&t|}||j|<|Srvrwryr)r)r*rzs    zSequenceOf._lazy_childcCst||jr|}nt|jtrBt|tr.|}qttdt|nrt|jtrt|tspttdt||jj t||js|}| |j |j |j ||_|}|}n |j|dSi}|jjr|jj|d<|jjr|jj |jj f|d<t||S)a  Constructs a _child_spec value from a native Python data type, or an appropriate Asn1Value object :param value: A native Python value, or some child of Asn1Value :return: An object of type _child_spec z Can not set a native python value to %s where the _child_spec is Any - value must be an instance of Asn1Value z Can not set a native python value to %s where the _child_spec is the choice type %s - value must be an instance of Asn1Value )r6r9r:)r0rrrr&r?r r rrrrDr2rGrr9r:r)rIr6rrrr)r)r*r~s:        zSequenceOf._make_valuecCs|jdkr|t|jS)rNr{rUr)r)r*rs zSequenceOf.__len__cCs|jdkr|||S)zm Allows accessing children via index :param key: Integer index of child N)rfrgrzrr)r)r*rs zSequenceOf.__getitem__cCs||jdkr|||}|t|jkrL|jd|jdk rL|jd||j|<|jdk rr|j|j|j|<d|_dS)z Allows overriding a child via index :param key: Integer index of child :param value: Native python datatype that will be passed to _child_spec to create new child object NT)rfrgr~rArrnrxrs)rIrr6rr)r)r*rs       zSequenceOf.__setitem__cCs>|jdkr||j||jdk r4|j|d|_dS)zk Allows removing a child via index :param key: Integer index of child NT)rfrgpoprnrsrr)r)r*r s    zSequenceOf.__delitem__ccs8|jdkr|tdt|jD]}||Vq"dS)zA :return: An iter() of child objects Nr)rfrgrrArz)rIrr)r)r*rs zSequenceOf.__iter__cCs\|dks|tkrdSt||js@ttdt|t|jt||D]}||krDdSqDdS)z :param item: An object of the type cls._child_spec :return: A boolean if the item is contained in this SequenceOf NFzy Checking membership in %s is only available for instances of %s, not %s T)rjr0rr1r r )rIitemrr)r)r* __contains__*s   zSequenceOf.__contains__cCsL|jdkr||j|||jdk rB|j|jdjd|_dS)z Allows adding a child to the end of the sequence :param value: Native python datatype that will be passed to _child_spec to create new child object Nr}T)rfrgrr~rnrxrsrr)r)r*rGs  zSequenceOf.appendcCsX|jdkr|t}|D]}||j|dq||_d|_|jdkrTd|_dS)z Encodes all child objects into the contents for this object :param force: Ensure all contents are in DER format instead of possibly using cached BER-encoded data Nrr+) rfrgrrrZrrrrrr)r)r*ro[s   zSequenceOf._set_contentsc Cszg|_|jdkrWdSt|j}d}||krt|j||d\}}|jrV||jf}n|}|rt|}t|ttfr|j dd|j |q&Wn\t t fk r}z:d|_|j dd}|j ddt|f||_ |W5d}~XYnXdS)aU Parses the contents and generates Asn1Value objects based on the definitions from _child_spec. :param recurse: If child objects that are Sequence or SequenceOf objects should be recursively parsed :raises: ValueError - when an error occurs parsing child objects NrrTrr r)rfrrArrrxr0rdrtrgrr?r1rHr )rIrrrrrrNrHr)r)r*rgos*    zSequenceOf._parse_childrencCs|jS)z Determines the spec to use for child values. :return: A child class of asn1crypto.core.Asn1Value that child values must be encoded using )rrUr)r)r*r.s zSequenceOf.specc Cs|jdkrdS|jdkr|jdkr.|jddzdd|D|_WnVttfk r}z4|jdd}|jddt|f||_|W5d}~XYnX|jS) z The native Python datatype representation of this value :return: A list or None. If a list, all child values are recursively converted to native representation also. NTrcSsg|] }|jqSr)r)rrr)r)r*rsz%SequenceOf.native..r rr)rGrnrfrgr?r1rHr )rIrNrHr)r)r*rxs    zSequenceOf.nativecsZtt||||jdk rVg|_|jD],}|jtkrD|j|q(|j|q(dS)a" Copies the contents of another SequenceOf object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects N)rrtrarfr<rrrbrrr)r*ras    zSequenceOf._copycCs@|jdkr|d|}t|||D]}||dq(dS)rrNrsr )rfrgrvrwrr)r)r*rws   zSequenceOf.debugcCs:|jdk r |jdddkr d}|r0|j|dt|S)r|Nr}r~Tr)rror&rZrr)r)r*rZs  zSequenceOf.dump)NNNN)F)F)r )F)!rrrrr2rDrFrfrrsrrOrrGrrnrzr~rrrrrrrrorgr.rxrarwrZrr)r)rr*rt's> +   7    $    rtc@s<eZdZdZdZdZdZdZddZd d d Z dd d Z dS)Setzm Represents a set of fields (unordered) from ASN.1 as a Python object with a dict-like interface r rNcCs"|j}i|_i|_g|_t|jD]N\}}t|dkrJ|if}||j|<||j|d<||jt|d|d<q"|jdk r|j|jd|j|jdf|_ t|jD]t\}}|j dk o|d|j k}|j dk o|j d|k}|s|r|j dq|j |d|d|d|ddfqdSr) r<rirrrrhrArrrrrrr)r)r*r8s$    "z Set._setupFc Cs,|j}|jdkr|jrtgt|j|_t|jD]b\}\}}}d|kr2|j|rh|j|\}}}} }n||\}}}} }| |||| d|j|<q2dSz2i} t|j } d} d} | | krt |j | | d\}} |d|df}|j |}|dkr$ttd| t |dt |d|d|j|p8||\}}}} }|dks`|rht|trh|}d}|r~||| |f}n ||| f}|rt|}t|ttfr|jdd || |<| d7} qt|j}td|D]}|| krq|j|p||\}}}} }|dks(|r0t|tr0|}d}d }| s@d}nFd | krZd| krZd}n,d | krnt| |<nd| kr|f| | |<|rttd |t|qg|_td|D]}|j| |qWnXttfk r&}z4|jdd}|jdd t|f||_|W5d}~XYnXdS)rNrMrrr!z Data for field %s (%s class, %s method, tag %s) does not match any of the field definitions r TrFrLzU Missing required field "%s" from %s r)r<rrhrjrArfrrr}r~rGrrrjr?r rBrrrrxr0rdrtrgrr rr1rH)rIrr4rr7rrrrrZ child_maprrZ seen_fieldrrrrrZ total_fieldsrmissingrNrHr)r)r*rgs                     zSet._parse_childrenc Cs|jdkr|g}t|jD]P\}}|j|d}|j|\}}}d|kr`|f||kr`q ||j|fq |jdddddd |D|_ d|_ |j dkrd|_ dS) ac Encodes all child objects into the contents for this object. This method is overridden because a Set needs to be encoded by removing defaulted fields and then sorting the fields by tag. :param force: Ensure all contents are in DER format instead of possibly using cached BER-encoded data NrrMcSs|dSrr))ctr)r)r*r+z#Set._set_contents..)rr+cSsg|] }|dqS)r r))rrr)r)r*rsz%Set._set_contents..) rfrgrrZrhrr2sortrrrr) rIrZchild_tag_encodingsrrZchild_encodingrr.rr)r)r*ros   zSet._set_contents)F)F) rrrrrFrDr2rr8rgror)r)r)r*rs orc@seZdZdZdZdddZdS)SetOfz~ Represents a set (unordered) of a single type of values from ASN.1 as a Python object with a list-like interface rFcCs\|jdkr|g}|D]}||j|dqdt||_d|_|jdkrXd|_dS)aD Encodes all child objects into the contents for this object. This method is overridden because a SetOf needs to be encoded by sorting the child encodings. :param force: Ensure all contents are in DER format instead of possibly using cached BER-encoded data Nrr+) rfrgrrZrrkrrr)rIrZchild_encodingsrr)r)r*ros  zSetOf._set_contentsN)F)rrrrr2ror)r)r)r*rsrc@seZdZdZdZdS) EmbeddedPdvz A sequence structure NrYr)r)r)r*rsrc@seZdZdZdZdZdS) NumericStringzK Represents a numeric string from ASN.1 as a Python unicode string rNrar)r)r)r*rsrc@seZdZdZdZdZdS)PrintableStringzM Represents a printable string from ASN.1 as a Python unicode string rNrar)r)r)r*rsrc@seZdZdZdZdZdS) TeletexStringzK Represents a teletex string from ASN.1 as a Python unicode string ZteletexNrar)r)r)r*rsrc@seZdZdZdZdS)VideotexStringzI Represents a videotex string from ASN.1 as a Python byte string NrYr)r)r)r*rsrc@seZdZdZdZdZdS) IA5StringzH Represents an IA5 string from ASN.1 as a Python unicode string asciiNrar)r)r)r*rsrc@s(eZdZdZeddZeddZdS) AbstractTimezK Represents a time from ASN.1 as a Python datetime.datetime object c CsFt|}|j|}|s,ttd|t||}d}|drHtj}nD|dr|ddkr`dnd}t |t t |dt |d pd d }|d rt t |d d t |d d}|ddkr|d9}n|ddkr|d9}t |d}nd }t |dt |dt |dt |dt |dp*d t |dp:d ||dS)z The parsed datetime string. :raises: ValueError - when an invalid value is passed :return: A dict with the parsed values z: Error parsing %s to a %s NZzuluZdsign+r r}ZdhourZdminuter)hoursminutesfractionr^i@Bminuteisecond<yearmonthdayhour)rrrrrrtzinfor)r_TIMESTRING_RErKr?r r groupdictrutcrrrrrAZlimit_denominator)rIstringmgroupstzsignZfractZ fract_usecr)r)r* _parsed_timesP            zAbstractTime._parsed_timecCsR|jdkrdS|jdkrL|j}|dd}||}|rF|t|d7}||_|jS)aF The native Python datatype representation of this value :return: A datetime.datetime object, asn1crypto.util.extended_datetime object or None. The datetime object is usually timezone aware. If it's naive, then it's in the sender's local time; see X.680 sect. 42.3 Nrr) microseconds)rGrnrr _get_datetimer)rIrtrr6r)r)r*rxBs    zAbstractTime.nativeN)rrrrrrrxr)r)r)r*rs  ?rc@s2eZdZdZdZedejZddZ ddZ dS) UTCTimez^ Represents a UTC time from ASN.1 as a timezone aware Python datetime.datetime object a  ^ # YYMMDD (?P\d{2}) (?P\d{2}) (?P\d{2}) # hhmm or hhmmss (?P\d{2}) (?P\d{2}) (?P\d{2})? # Matches nothing, needed because GeneralizedTime uses this. (?P) # Z or [-+]hhmm (?: (?PZ) | (?: (?P[-+]) (?P\d{2}) (?P\d{2}) ) ) $ cCspt|trZ|jstd|t}d|jkr8dksBntd|d}trZ| d}t ||d|_ dS)z Sets the value of the object :param value: A unicode string or a datetime.datetime object :raises: ValueError - when an invalid value is passed Must be timezone awareiizMYear of the UTCTime is not in range [1950, 2049], use GeneralizedTime insteadz %y%m%d%H%M%SZrN) r0rrr? astimezonerrstrftimerRrrrErnrr)r)r*rEs     z UTCTime.setcCs8|ddkr|dd7<n|dd7<tf|S)z Create a datetime object from the parsed time. :return: An aware datetime.datetime object r2iil)rrIrtr)r)r*rs zUTCTime._get_datetimeN rrrrr2recompileXrrErr)r)r)r*r_src@s2eZdZdZdZedejZddZ ddZ dS) GeneralizedTimez Represents a generalized time from ASN.1 as a Python datetime.datetime object or asn1crypto.util.extended_datetime object in UTC aO ^ # YYYYMMDD (?P\d{4}) (?P\d{2}) (?P\d{2}) # hh or hhmm or hhmmss (?P\d{2}) (?: (?P\d{2}) (?P\d{2})? )? # Optional fraction; [.,]dddd (one or more decimals) # If Seconds are given, it's fractions of Seconds. # Else if Minutes are given, it's fractions of Minutes. # Else it's fractions of Hours. (?: [,.] (?P\d+) )? # Optional timezone. If left out, the time is in local time. # Z or [-+]hh or [-+]hhmm (?: (?PZ) | (?: (?P[-+]) (?P\d{2}) (?P\d{2})? ) )? $ cCst|ttfrl|jstd|t}|jrHdt|j d d}nd}| d|d}t rl| d}t||d |_d S) a Sets the value of the object :param value: A unicode string, a datetime.datetime object or an asn1crypto.util.extended_datetime object :raises: ValueError - when an invalid value is passed rrMrFrrz %Y%m%d%H%M%SZrN)r0rrrr?rr microsecondstrzfillrrrRrrrErn)rIr6rr)r)r*rEs    zGeneralizedTime.setcCs$|ddkrtf|Stf|SdS)z Create a datetime object from the parsed time. :return: A datetime.datetime object or asn1crypto.util.extended_datetime object. It may or may not be aware. rrN)rrrr)r)r*rs  zGeneralizedTime._get_datetimeNrr)r)r)r*rs#%!rc@seZdZdZdZdZdS) GraphicStringzK Represents a graphic string from ASN.1 as a Python unicode string rNrar)r)r)r*rsrc@seZdZdZdZdZdS) VisibleStringzK Represents a visible string from ASN.1 as a Python unicode string rNrar)r)r)r*rsrc@seZdZdZdZdZdS) GeneralStringzK Represents a general string from ASN.1 as a Python unicode string rNrar)r)r)r*r'src@seZdZdZdZdZdS)UniversalStringzM Represents a universal string from ASN.1 as a Python unicode string z utf-32-beNrar)r)r)r*r1src@seZdZdZdZdZdS)CharacterStringzM Represents a character string from ASN.1 as a Python unicode string rNrar)r)r)r*r:src@seZdZdZdZdZdS) BMPStringzG Represents a BMP string from ASN.1 as a Python unicode string z utf-16-beNrar)r)r)r*rDsrcCs\td|t|t|f|jrBtd|t|jp2ddf|jdk o^|jdk o^|j dk }|r|t |j}t |j}|j dk r|j D] \}}td|t ||fq|rtd||||j fn>|jr|rtd||||j fn|rtd ||||j f|jr4td |t|jp$ddftd |t|jpHddfdS) a7 Prints out basic information about an Asn1Value object. Extracted for reuse among different classes that customize the debug information. :param prefix: A unicode string of spaces to prefix output line with :param self: The object to print the debugging information about rz%s Header: 0x%sr+r\Nz#%s %s tag %s (explicitly tagged)z%s %s %s %sz&%s %s %s tag %s (implicitly tagged)z%s %s %s tag %sz%s Trailer: 0x%sz%s Data: 0x%s)ryr rYrbinasciihexlifyrrFrDr2rrjrBr9r:rrG)r{rI has_header method_name class_namerDr2r)r)r*rvMs6 "   $rvcCspd|krl|ddkr.|dd|df|d<n$|ddkrR|dd|df|d<|d=|d=d|krl|d=dS)z Converts old-style "tag_type" and "tag" params to "explicit" and "implicit" :param params: A dict of parameters to convert from tag_type/tag to explicit/implicit rKr9classr!r2r:N)rj)rr)r)r*r|s  rcCst|d}d|kr$|jdk rxd}nTt|dtr@|d\}}n |d}d}|jdkr\d}n|jt|kst|j|krxd}|d|jkrd}|r| |S|S)z Checks if a value is properly tagged based on the spec, and re/untags as necessary :param value: An Asn1Value object :param params: A dict of spec params :return: An Asn1Value that is properly tagged Fr:Trr9) rr:r0rrDrCr2rjr9rk)r6rrkrDr2r)r)r*rs$   rcCs|dkr dS|j}|j}t|d|krRt|dtrD|d\}}qd}|d}n0d|krt|dtrv|d\}}n d}|d}|dk rt|tst|}|d|}|d|}||fS)aP Builds a 2-element tuple used to identify fields by grabbing the class_ and tag from an Asn1Value class and the params dict being passed to it :param params: A dict of params to pass to spec :param spec: An Asn1Value class :return: A 2-element integer tuple in the form (class_, tag) N)NNr9r!r:rDr2)rDr2rr0rrrCrj)rr.Zrequired_classZ required_tagr)r)r*rs(   rcCsJ|s |s dStttt|d|}t||krFtdt|||S)z Format value as a tuple of 1s and 0s. :param value: A non-negative integer to format :param bits: Number of bits in the output :return: A tuple of 1s and 0s with bits members. r)z0{0}bzResult too large: {0} > {1})rrrrrAr?)r6rresultr)r)r*rs  r)r r!rr7rCrFrrr\r^rr`rcrerrrrrrrrrrrrrrc  Cs|dk rt||dkrtSd} |dk r:|o4d|k} | s|jsR|rd|kr|rb|f|} n|} | j} t| } |}|}|}|}|}|pd}| D]\}}||krttdt| t|t|||dkrttdt| t dt ||||krttd t| ||t |t |\}}|\}}}}}}t | t s||7}||}qt||dd id } || _|| _| | _d } qr|r|fd |i|} n ||d } |tkrqrt | t rF| |||z|| j| _d}| WnXttfk rB}z4|jdd}|jddt| f||_|W5d}~XYnXn|| jkrxttdt| t| jt|||| jkr|dko| jdko|dk}|rt | tsttdt| t | jt ||n || _d | _|| jkrrt | jtr|| jk}n || jk}|srttdt| | j|n8|rd|krtfd |i|}|j} |}|}|prd}t| D]<\}}t |t |\}}|\}}}}}}||7}||}q|t||dd id } || j| _| j|pd7_| | _d } nx|tkr"ttdt|t ||t|}|||d} |dkoR| jdkoR|dk}|rlt | trld | _|| _| s|| _|pd| _d| _ |rz| |WnXttfk r}z4|jdd}|jddt| f||_|W5d}~XYnX| S)a Builds an Asn1Value object generically, or using a spec with optional params :param class_: An integer representing the ASN.1 class :param method: An integer representing the ASN.1 method :param tag: An integer representing the ASN.1 tag :param header: A byte string of the ASN.1 header (class, method, tag, length) :param contents: A byte string of the ASN.1 value :param trailer: A byte string of any ASN.1 trailer (only used by indefinite length encodings) :param spec: A class derived from Asn1Value that defines what class_ and tag the value should have, and the semantics of the encoded value. The return value will be of this type. If omitted, the encoded value will be decoded using the standard universal tag based on the encoded tag number. :param spec_params: A dict of params to pass to the spec object :param nested_spec: For certain Asn1Value classes (such as OctetString and BitString), the contents can be further parsed and interpreted as another Asn1Value. This parameter controls the spec for that sub-parsing. :return: An object of the type spec, or if not specified, a child of Asn1Value NFrJr9r+z Error parsing %s - explicitly-tagged class should have been %s, but %s was found r z Error parsing %s - explicitly-tagged method should have been %s, but %s was found z Error parsing %s - explicitly-tagged tag should have been %s, but %s was found TrrGrrrz Error parsing %s - class should have been %s, but %s was found szy Error parsing %s - method should have been %s, but %s was found zv Error parsing %s - tag should have been %s, but %s was found zO Unknown element - %s class, %s method, tag %s )rGrD)!rrjr9reversedr?r r rBrjrrrAr0rrxrrrrrGrr1rHrDrFrrr2rrr&_UNIVERSAL_SPECSrn)rDrFr2rrGtrailerr.r/Z nested_specZ header_setrJr6Zoriginal_explicitZ explicit_infoZ parsed_classZ parsed_methodZ parsed_tagZto_parseZexplicit_headerZexplicit_trailerZexpected_classZ expected_tagrr7Z parsed_headerZparsed_trailerrNrHZ ber_indefZ is_bad_tagoriginal_valuer)r)r*rxs)                                  rxc CsTt|}t|||\}}|r@|||kr@|||}td|t|||d|fS)a Parses a byte string generically, or using a spec with optional params :param encoded_data: A byte string that contains BER-encoded data :param pointer: The index in the byte string to parse from :param spec: A class derived from Asn1Value that defines what class_ and tag the value should have, and the semantics of the encoded value. The return value will be of this type. If omitted, the encoded value will be decoded using the standard universal tag based on the encoded tag number. :param spec_params: A dict of params to pass to the spec object :param strict: A boolean indicating if trailing data should be forbidden - if so, a ValueError will be raised when trailing data exists :return: A 2-element tuple: - 0: An object of the type spec, or if not specified, a child of Asn1Value - 1: An integer indicating how many bytes were consumed rr)rArr?rx) r(rr.r/r%Z encoded_lenrZ new_pointerrr)r)r*r3s   r3)F)NNN)rNNF)nr __future__rrrrrrZ fractionsrrrbrrsysrr _errorsr Z _ordereddictr _typesr rrrrparserrrutilrrrrrr version_info cStringIOrrxrangerrRioregisterrBrCrrrJr=r'objectr&rrrrrjrrrrrrrrrr$r0r6r<r@rArBrDrXrZr[r]r_rbrdrtrrrrrrrrrrrrrrrrrrvrrrrrrxr3r)r)r)r*s*.           6e,Q6V#Q5QlANQ34bD  ?J;!    bV_      /(- j