U +Mb{@sddlZddlmZmZmZmZddlmZmZdddddd d d gZ dd dZ Gddde Z Gddde Z Gddde ZGddde ZGddde ZGddde ZGdd d e ZGdd d e ZGdd d e ZdS)N) byte_stringbbchrbord) long_to_bytes bytes_to_long DerObject DerIntegerDerOctetStringDerNull DerSequence DerObjectId DerBitStringDerSetOfFcCs6d}z ||}Wntk r&YdSX| p4|dkS)NrF) TypeError)xonly_non_negativetestr7/tmp/pip-target-t616c12r/lib/python/Crypto/Util/asn1.py _is_number!s  rc@s@eZdZdZddZddZddZdd Zd d Zd d Z dS) BytesIO_EOFzeThis class differs from BytesIO in that a ValueError exception is raised whenever EOF is reached.cCs||_d|_d|_dSNr)_buffer_index _bookmark)selfZ initial_bytesrrr__init__.szBytesIO_EOF.__init__cCs |j|_dSN)rrrrrr set_bookmark3szBytesIO_EOF.set_bookmarkcCs |jdk st|j|j|jSr)rAssertionErrorrrrrrrdata_since_bookmark6szBytesIO_EOF.data_since_bookmarkcCst|j|jSr)lenrrrrrrremaining_data:szBytesIO_EOF.remaining_datacCsH|j|}|t|jkr.td|t|jf|j|j|}||_|S)Nz@Not enough data for DER decoding: expected %d bytes and found %d)rr#r ValueError)rlengthZ new_indexresultrrrread=s  zBytesIO_EOF.readcCst|ddS)Nr)rr(rrrr read_byteFszBytesIO_EOF.read_byteN) __name__ __module__ __qualname____doc__rr r"r$r(r*rrrrr*s rc@sPeZdZdZdddZddZed d Zd d Zd dZ dddZ ddZ dS)rzpBase class for defining a single DER object. This class should never be directly instantiated. NFcCs|dkrd|_dS||}||_d||fkr6td|dk rZdd|B||B|_dS|dk rd||B|_d||B|_dSd||B|_dS)aInitialize the DER object according to a specific ASN.1 type. :Parameters: asn1Id : integer The universal DER tag number for this object (e.g. 0x10 for a SEQUENCE). If None, the tag is not known yet. payload : byte string The initial payload of the object (that it, the content octets). If not specified, the payload is empty. implicit : integer The IMPLICIT tag number to use for the encoded object. It overrides the universal tag *asn1Id*. constructed : bool True when the ASN.1 type is *constructed*. False when it is *primitive*. explicit : integer The EXPLICIT tag number to use for the encoded object. Nz1Explicit and implicit tags are mutually exclusive ) _tag_octet _convertTagpayloadr%_inner_tag_octet)rZasn1Idr5implicitZ constructedexplicitrrrrPs  zDerObject.__init__cCsJt|s t|dkr t|d}t|r>d|krrr6r$)rr@rEZidOctetr&pZ inner_octetrrrrCs            zDerObject._decodeFromStream)Nr/NFN)F) r+r,r-r.rr4 staticmethodr=r?rArFrCrrrrrJs ?   c@s4eZdZdZd ddZddZdd d Zd d ZdS)r aClass to model a DER INTEGER. An example of encoding is:: >>> from Crypto.Util.asn1 import DerInteger >>> from binascii import hexlify, unhexlify >>> int_der = DerInteger(9) >>> print hexlify(int_der.encode()) which will show ``020109``, the DER encoding of 9. And for decoding:: >>> s = unhexlify(b'020109') >>> try: >>> int_der = DerInteger() >>> int_der.decode(s) >>> print int_der.value >>> except ValueError: >>> print "Not a valid DER INTEGER" the output will be ``9``. :ivar value: The integer value :vartype value: integer rNcCst|dd|d|||_dS)aUInitialize the DER object as an INTEGER. :Parameters: value : integer The value of the integer. implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for INTEGER (2). r/FNrrvaluerrKr7r8rrrrs zDerInteger.__init__cCsz|j}d|_tt|d@|j|_d|kr8dkrLnntd|j|_d|kr`dkrfqpnqp|dL}q t|S)zIReturn the DER INTEGER, fully encoded as a binary string.r/r0ri)rKr5rintrr?)rnumberrrrr?%s zDerInteger.encodeFcCstj|||dS)a!Decode a complete DER INTEGER DER, and re-initializes this object with it. Args: der_encoded (byte string): A complete INTEGER DER element. Raises: ValueError: in case of parsing errors. rErrFrrDrErrrrF4s zDerInteger.decodecCst||||r\t|jdkr(tdt|jdkr\td|jddddkr\tdd|_d}|jD],}|jd 9_|jt|7_|d K}ql|jrt|jdd@r|j|8_dS) z*Decode a complete DER INTEGER from a file.rz/Invalid encoding for DER INTEGER: empty payloadrIz>HNr0z.Invalid encoding for DER INTEGER: leading zeror)rN) rrCr#r5r%structunpackrKr)rr@rEbitsirrrrCAs,  zDerInteger._decodeFromStream)rNN)Fr+r,r-r.rr?rFrCrrrrr s   c@seZdZdZd#ddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ d$ddZd%ddZddZd&dd Zd!d"ZdS)'r aClass to model a DER SEQUENCE. This object behaves like a dynamic Python sequence. Sub-elements that are INTEGERs behave like Python integers. Any other sub-element is a binary string encoded as a complete DER sub-element (TLV). An example of encoding is: >>> from Crypto.Util.asn1 import DerSequence, DerInteger >>> from binascii import hexlify, unhexlify >>> obj_der = unhexlify('070102') >>> seq_der = DerSequence([4]) >>> seq_der.append(9) >>> seq_der.append(obj_der.encode()) >>> print hexlify(seq_der.encode()) which will show ``3009020104020109070102``, the DER encoding of the sequence containing ``4``, ``9``, and the object with payload ``02``. For decoding: >>> s = unhexlify(b'3009020104020109070102') >>> try: >>> seq_der = DerSequence() >>> seq_der.decode(s) >>> print len(seq_der) >>> print seq_der[0] >>> print seq_der[:] >>> except ValueError: >>> print "Not a valid DER SEQUENCE" the output will be:: 3 4 [4, 9, b''] NcCs,t|dd|d|dkr"g|_n||_dS)aInitialize the DER object as a SEQUENCE. :Parameters: startSeq : Python sequence A sequence whose element are either integers or other DER objects. implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for SEQUENCE (16). r/TN)rr_seq)rZstartSeqr7rrrrs zDerSequence.__init__cCs |j|=dSrr[rnrrr __delitem__szDerSequence.__delitem__cCs |j|Srr\r]rrr __getitem__szDerSequence.__getitem__cCs||j|<dSrr\)rkeyrKrrr __setitem__szDerSequence.__setitem__cCs||j||<dSrr\)rrXjsequencerrr __setslice__szDerSequence.__setslice__cCs|j||=dSrr\rrXrcrrr __delslice__szDerSequence.__delslice__cCs|jtd|td|Sr)r[maxrfrrr __getslice__szDerSequence.__getslice__cCs t|jSrr#r[rrrr__len__szDerSequence.__len__cCs|j||Srr[appendritemrrr__iadd__s zDerSequence.__iadd__cCs|j||Srrlrnrrrrms zDerSequence.appendTcsfdd|jD}t|S)zReturn the number of items in this sequence that are integers. Args: only_non_negative (boolean): If ``True``, negative integers are not counted in. csg|]}t|r|qSr)r.0rrrr s z'DerSequence.hasInts..)r[r#)rritemsrrsrhasIntss zDerSequence.hasIntscCs|jo||t|jkS)aReturn ``True`` if all items in this sequence are integers or non-negative integers. This function returns False is the sequence is empty, or at least one member is not an integer. Args: only_non_negative (boolean): If ``True``, the presence of negative integers causes the method to return ``False``.)r[rvr#)rrrrr hasOnlyIntss zDerSequence.hasOnlyIntscCsfd|_|jD]N}t|r(|j|7_q t|rH|jt|7_q |j|7_q t|S)zReturn this DER SEQUENCE, fully encoded as a binary string. Raises: ValueError: if some elements in the sequence are neither integers nor byte strings. r/)r5r[rrr r?rrnrrrr?s zDerSequence.encodeFcCs.||_tj|||d}|r*|s*td|S)a9Decode a complete DER SEQUENCE, and re-initializes this object with it. Args: der_encoded (byte string): A complete SEQUENCE DER element. nr_elements (None or integer or list of integers): The number of members the SEQUENCE can have only_ints_expected (boolean): Whether the SEQUENCE is expected to contain only integers. strict (boolean): Whether decoding must check for strict DER compliancy. Raises: ValueError: in case of parsing errors. DER INTEGERs are decoded into Python integers. Any other DER element is not decoded. Its validity is not checked. rQzSome members are not INTEGERs) _nr_elementsrrFrwr%)rrDrEZ nr_elementsZonly_ints_expectedr'rrrrFs  zDerSequence.decodecCsg|_t|||t|j}|dkr|t}||||jdkr`|j| qt }| }|j ||d|j|j qd}|j dk rzt|j|j k}Wn$tk rt|j|j k}YnX|stdt|jdS)z+Decode a complete DER SEQUENCE from a file.rrIrQTNz1Unexpected number of members (%d) in the sequence)r[rrCrr5r$r r3rmr"r rFrKrxr#rr%)rr@rErGderderIntdataokrrrrCs.     zDerSequence._decodeFromStream)NN)T)T)FNF)r+r,r-r.rr_r`rbrergrirkrprmrvrwr?rFrCrrrrr Xs *   c@seZdZdZdddZdS)r aClass to model a DER OCTET STRING. An example of encoding is: >>> from Crypto.Util.asn1 import DerOctetString >>> from binascii import hexlify, unhexlify >>> os_der = DerOctetString(b'\xaa') >>> os_der.payload += b'\xbb' >>> print hexlify(os_der.encode()) which will show ``0402aabb``, the DER encoding for the byte string ``b'\xAA\xBB'``. For decoding: >>> s = unhexlify(b'0402aabb') >>> try: >>> os_der = DerOctetString() >>> os_der.decode(s) >>> print hexlify(os_der.payload) >>> except ValueError: >>> print "Not a valid DER OCTET STRING" the output will be ``aabb``. :ivar payload: The content of the string :vartype payload: byte string r/NcCst|d||ddS)ahInitialize the DER object as an OCTET STRING. :Parameters: value : byte string The initial payload of the object. If not specified, the payload is empty. implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for OCTET STRING (4). FNrr)rrKr7rrrrAs zDerOctetString.__init__)r/Nr+r,r-r.rrrrrr #sc@seZdZdZddZdS)r z"Class to model a DER NULL element.cCst|dddddS)z$Initialize the DER object as a NULL.r/NFr~rrrrrSszDerNull.__init__Nrrrrrr Psc@s4eZdZdZd ddZddZdd d Zd d ZdS)r a(Class to model a DER OBJECT ID. An example of encoding is: >>> from Crypto.Util.asn1 import DerObjectId >>> from binascii import hexlify, unhexlify >>> oid_der = DerObjectId("1.2") >>> oid_der.value += ".840.113549.1.1.1" >>> print hexlify(oid_der.encode()) which will show ``06092a864886f70d010101``, the DER encoding for the RSA Object Identifier ``1.2.840.113549.1.1.1``. For decoding: >>> s = unhexlify(b'06092a864886f70d010101') >>> try: >>> oid_der = DerObjectId() >>> oid_der.decode(s) >>> print oid_der.value >>> except ValueError: >>> print "Not a valid DER OBJECT ID" the output will be ``1.2.840.113549.1.1.1``. :ivar value: The Object ID (OID), a dot separated list of integers :vartype value: string NcCst|dd|d|||_dS)aInitialize the DER object as an OBJECT ID. :Parameters: value : string The initial Object Identifier (e.g. "1.2.0.0.6.2"). implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for OBJECT ID (6). explicit : integer The EXPLICIT tag to use for the encoded object. r/FNrJrLrrrrws zDerObjectId.__init__cCsdd|jdD}t|dkr*tdtd|d|d|_|dd D]h}|dkrddg}n6g}|r|d|d @d B|d L}qh|d d M<|jddd|D7_qPt |S)zCReturn the DER OBJECT ID, fully encoded as a binary string.cSsg|] }t|qSr)rOrqrrrrtsz&DerObjectId.encode...rIz$Not a valid Object Identifier string(rr)Nr;r0r/cSsg|] }t|qSr)rrqrrrrts) rKsplitr#r%rr5insertjoinrr?)rcompsvencrrrr?s   zDerObjectId.encodeFcCst|||S)abDecode a complete DER OBJECT ID, and re-initializes this object with it. Args: der_encoded (byte string): A complete DER OBJECT ID. strict (boolean): Whether decoding must check for strict DER compliancy. Raises: ValueError: in case of parsing errors. rRrSrrrrFszDerObjectId.decodecCst|||t|j}ddt|dD}d}|rp|}|d|d@}|d@s4|t|d}q4d ||_ dS) z,Decode a complete DER OBJECT ID from a file.cSsg|] }t|qSr)strrqrrrrtsz1DerObjectId._decodeFromStream..rrr0r;rN) rrCrr5divmodr*r$rmrrrK)rr@rErGrrcrrrrCs zDerObjectId._decodeFromStream)rNN)FrYrrrrr Ys   c@s4eZdZdZd ddZddZdd d Zd d ZdS)raClass to model a DER BIT STRING. An example of encoding is: >>> from Crypto.Util.asn1 import DerBitString >>> bs_der = DerBitString(b'\xAA') >>> bs_der.value += b'\xBB' >>> print(bs_der.encode().hex()) which will show ``030300aabb``, the DER encoding for the bit string ``b'\xAA\xBB'``. For decoding: >>> s = bytes.fromhex('030300aabb') >>> try: >>> bs_der = DerBitString() >>> bs_der.decode(s) >>> print(bs_der.value.hex()) >>> except ValueError: >>> print "Not a valid DER BIT STRING" the output will be ``aabb``. :ivar value: The content of the string :vartype value: byte string r/NcCs4t|dd|d|t|tr*||_n||_dS)aInitialize the DER object as a BIT STRING. :Parameters: value : byte string or DER object The initial, packed bit string. If not specified, the bit string is empty. implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for OCTET STRING (3). explicit : integer The EXPLICIT tag to use for the encoded object. r/FN)rr isinstancer?rKrLrrrrs   zDerBitString.__init__cCsd|j|_t|S)zBReturn the DER BIT STRING, fully encoded as a byte string.)rKr5rr?rrrrr?s zDerBitString.encodeFcCst|||S)aTDecode a complete DER BIT STRING, and re-initializes this object with it. Args: der_encoded (byte string): a complete DER BIT STRING. strict (boolean): Whether decoding must check for strict DER compliancy. Raises: ValueError: in case of parsing errors. rRrSrrrrFs zDerBitString.decodecCsNt||||jr.t|jddkr.tdd|_|jrJ|jdd|_dS)z1Decode a complete DER BIT STRING DER from a file.rzNot a valid BIT STRINGr/r)N)rrCr5rr%rK)rr@rErrrrCs zDerBitString._decodeFromStream)r/NN)FrYrrrrrs   c@sTeZdZdZdddZddZddZd d Zd d ZdddZ ddZ ddZ dS)raClass to model a DER SET OF. An example of encoding is: >>> from Crypto.Util.asn1 import DerBitString >>> from binascii import hexlify, unhexlify >>> so_der = DerSetOf([4,5]) >>> so_der.add(6) >>> print hexlify(so_der.encode()) which will show ``3109020104020105020106``, the DER encoding of a SET OF with items 4,5, and 6. For decoding: >>> s = unhexlify(b'3109020104020105020106') >>> try: >>> so_der = DerSetOf() >>> so_der.decode(s) >>> print [x for x in so_der] >>> except ValueError: >>> print "Not a valid DER SET OF" the output will be ``[4, 5, 6]``. NcCs:t|dd|dg|_d|_|r6|D]}||q&dS)a9Initialize the DER object as a SET OF. :Parameters: startSet : container The initial set of integers or DER encoded objects. implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for SET OF (17). r/TN)rrr[ _elemOctetadd)rZstartSetr7errrr1s zDerSetOf.__init__cCs |j|Srr\r]rrrr`FszDerSetOf.__getitem__cCs t|jSr)iterr[rrrr__iter__IszDerSetOf.__iter__cCs t|jSrrjrrrrrkLszDerSetOf.__len__cCsht|rd}nt|tr |j}n t|d}|j|krN|jdk rHtd||_||jkrd|j|dS)zAdd an element to the set. Args: elem (byte string or integer): An element of the same type of objects already in the set. It can be an integer or a DER encoded object. rIrNz&New element does not belong to the set) rrrr3rrr%r[rm)relemeorrrrOs      z DerSetOf.addFcCst|||S)aDecode a complete SET OF DER element, and re-initializes this object with it. DER INTEGERs are decoded into Python integers. Any other DER element is left undecoded; its validity is not checked. Args: der_encoded (byte string): a complete DER BIT SET OF. strict (boolean): Whether decoding must check for strict DER compliancy. Raises: ValueError: in case of parsing errors. rRrSrrrrFgszDerSetOf.decodecCsg|_t|||t|j}d}|dkr|t}||||dkrX|j}n||jkrjtd|dkr|j | q"t }| | ||j |j q"dS)z)Decode a complete DER SET OF from a file.rrz)Not all elements are of the same DER typerIN)r[rrCrr5r$r r3r%rmr"r rFrK)rr@rErGZ setIdOctetryrzrrrrCys"    zDerSetOf._decodeFromStreamcCsfg}|jD]<}t|r$t|}nt|tr8|}n|}||q |d||_ t|S)zRReturn this SET OF DER element, fully encoded as a binary string. r/) r[rr r?rrrmsortrr5)rZorderedroZbysrrrr?s     zDerSetOf.encode)NN)F) r+r,r-r.rr`rrkrrFrCr?rrrrrs  !)F)rUZCrypto.Util.py3compatrrrrZCrypto.Util.numberrr__all__robjectrrr r r r r rrrrrrs(  0_L- dY