3
¬ �eI�  ã            	   @   sð   d dl Z d dlmZmZmZ d dlmZmZ dddddd	d
ddg	Zddd„Z	G dd„ de
ƒZG dd„ de
ƒZG dd„ deƒZG dd„ deƒZG dd	„ d	eƒZG dd„ deƒZG dd„ deƒZG dd
„ d
eƒZG dd„ deƒZG dd„ deƒZdS )é    N)Úbyte_stringÚbchrÚbord)Úlong_to_bytesÚbytes_to_longÚ	DerObjectÚ
DerIntegerÚ
DerBooleanÚDerOctetStringÚDerNullÚDerSequenceÚDerObjectIdÚDerBitStringÚDerSetOfFc             C   s4   d}y| | }W n t k
r$   dS X | p2| dkS )Nr   F)Ú	TypeError)ÚxÚonly_non_negativeÚtest© r   úW/var/www/html/wholesaler-api-python-env/lib/python3.6/site-packages/Crypto/Util/asn1.pyÚ
_is_number(   s    r   c               @   s@   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dS )ÚBytesIO_EOFzeThis class differs from BytesIO in that a ValueError exception is
    raised whenever EOF is reached.c             C   s   || _ d| _d | _d S )Nr   )Ú_bufferÚ_indexÚ	_bookmark)ÚselfZinitial_bytesr   r   r   Ú__init__5   s    zBytesIO_EOF.__init__c             C   s   | j | _d S )N)r   r   )r   r   r   r   Úset_bookmark:   s    zBytesIO_EOF.set_bookmarkc             C   s    | j d k	st‚| j| j | j… S )N)r   ÚAssertionErrorr   r   )r   r   r   r   Údata_since_bookmark=   s    zBytesIO_EOF.data_since_bookmarkc             C   s   t | jƒ| j S )N)Úlenr   r   )r   r   r   r   Úremaining_dataA   s    zBytesIO_EOF.remaining_datac             C   sH   | j | }|t| jƒkr.td|t| jƒf ƒ‚| j| j |… }|| _ |S )Nz@Not enough data for DER decoding: expected %d bytes and found %d)r   r    r   Ú
ValueError)r   ÚlengthZ	new_indexÚresultr   r   r   ÚreadD   s    
zBytesIO_EOF.readc             C   s   t | jdƒd ƒS )Né   r   )r   r%   )r   r   r   r   Ú	read_byteM   s    zBytesIO_EOF.read_byteN)
Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r!   r%   r'   r   r   r   r   r   1   s   	r   c               @   sP   e Zd ZdZddd„Zdd„ Zed	d
„ ƒZdd„ Zdd„ Z	ddd„Z
dd„ ZdS )r   zpBase class for defining a single DER object.

        This class should never be directly instantiated.
        Nó    Fc             C   s’   |dkrd| _ dS | j|ƒ}|| _|r*dnd}d||fkrBtdƒ‚|dk	r`d|B | j|ƒB | _ n.|dk	r„d| j|ƒB | _ ||B | _n
||B | _ dS )aù  Initialize the DER object according to a specific ASN.1 type.

                :Parameters:
                  asn1Id : integer or byte
                    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 or byte
                    The IMPLICIT tag number (< 0x1F) to use for the encoded object.
                    It overrides the universal tag *asn1Id*.
                    It cannot be combined with the ``explicit`` parameter.
                    By default, there is no IMPLICIT tag.

                  constructed : bool
                    True when the ASN.1 type is *constructed*.
                    False when it is *primitive* (default).

                  explicit : integer or byte
                    The EXPLICIT tag number (< 0x1F) to use for the encoded object.
                    It cannot be combined with the ``implicit`` parameter.
                    By default, there is no EXPLICIT tag.
                Né    r   z1Explicit and implicit tags are mutually exclusiveé€   é    )Ú
_tag_octetÚ_convertTagÚpayloadr"   Ú_inner_tag_octet)r   Zasn1Idr2   ÚimplicitZconstructedÚexplicitZconstructed_bitr   r   r   r   W   s    
zDerObject.__init__c             C   sL   t |ƒs t|ƒdkr t|d ƒ}t |ƒo>d|  ko:dk n  sHtdƒ‚|S )zCheck if *tag* is a real DER tag (5 bits).
                Convert it from a character to number if necessary.
                r&   r   é   zWrong DER tag)r   r    r   r"   )r   Útagr   r   r   r1   �   s     zDerObject._convertTagc             C   s,   | dkr$t | ƒ}tt|ƒd ƒ| S t| ƒS )zXBuild length octets according to BER/DER
                definite form.
                é   r.   )r   r   r    )r#   Úencodingr   r   r   Ú_definite_form©   s    zDerObject._definite_formc             C   sL   | j }t| dƒr0t| jƒ| jt| j ƒƒ | j  }t| jƒ| jt|ƒƒ | S )z?Return this DER element, fully encoded as a binary byte string.r3   )r2   Úhasattrr   r3   r:   r    r0   )r   Zoutput_payloadr   r   r   Úencode³   s    
zDerObject.encodec             C   sR   |j ƒ }|dkrN|j|d@ ƒ}t|d ƒdkr6tdƒ‚t|ƒ}|dkrNtdƒ‚|S )z%Decode DER length octets from a file.r8   r   z$Invalid DER: length has leading zeroz5Invalid DER: length in long form but smaller than 128)r'   r%   r   r"   r   )r   Úsr#   Zencoded_lengthr   r   r   Ú
_decodeLenÆ   s    zDerObject._decodeLenc             C   s<   t |ƒstdƒ‚t|ƒ}| j||ƒ |jƒ dkr8tdƒ‚| S )a  Decode a complete DER element, and re-initializes this
                object with it.

                Args:
                  der_encoded (byte string): A complete DER element.

                Raises:
                  ValueError: in case of parsing errors.
                zInput is not a byte stringr   z-Unexpected extra data after the DER structure)r   r"   r   Ú_decodeFromStreamr!   )r   Úder_encodedÚstrictr=   r   r   r   ÚdecodeÕ   s    zDerObject.decodec             C   sž   |j ƒ }| jdk	r&|| jkr,tdƒ‚n|| _| j|ƒ}|j|ƒ| _t| dƒršt| jƒ}|j ƒ }|| jkrptdƒ‚| j|ƒ}|j|ƒ| _|j	ƒ dkrštdƒ‚dS )z*Decode a complete DER element from a file.NzUnexpected DER tagr3   zUnexpected internal DER tagr   z-Unexpected extra data after the DER structure)
r'   r0   r"   r>   r%   r2   r;   r   r3   r!   )r   r=   rA   ZidOctetr#   ÚpZinner_octetr   r   r   r?   ì   s     







zDerObject._decodeFromStream)Nr,   NFN)F)r(   r)   r*   r+   r   r1   Ústaticmethodr:   r<   r>   rB   r?   r   r   r   r   r   Q   s    
E

c               @   s4   e Zd ZdZddd„Zdd„ Zdd	d
„Zdd„ ZdS )r   aÈ  Class 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
        r   Nc             C   s   t j| dd|d|ƒ || _dS )aU  Initialize 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,   FN)r   r   Úvalue)r   rF   r4   r5   r   r   r   r   #  s    zDerInteger.__init__c             C   s~   | j }d| _xftt|d@ ƒƒ| j | _d|  ko8dkn  rNtdƒ| j | _d|  ko`dkn  rhP |dL }qW tj| ƒS )zIReturn the DER INTEGER, fully encoded as a
                binary string.r,   éÿ   r.   r   é   i€ÿÿÿ)rF   r2   r   Úintr   r<   )r   Únumberr   r   r   r<   3  s    zDerInteger.encodeFc             C   s   t j| ||d�S )a  Decode a DER-encoded INTEGER, and re-initializes this
                object with it.

                Args:
                  der_encoded (byte string): A complete INTEGER DER element.

                Raises:
                  ValueError: in case of parsing errors.
                )rA   )r   rB   )r   r@   rA   r   r   r   rB   B  s    zDerInteger.decodec             C   sÈ   t j| ||ƒ |r\t| jƒdkr(tdƒ‚t| jƒdkr\tjd| jdd… ƒd dk r\tdƒ‚d| _d}x6| jD ],}|  jd	9  _|  jt|ƒ7  _|d
K }qnW | jrÄt| jd ƒd@ rÄ|  j|8  _dS )z*Decode a complete DER INTEGER from a file.r   z/Invalid encoding for DER INTEGER: empty payloadrE   z>HNr.   z.Invalid encoding for DER INTEGER: leading zeror&   é   rH   )	r   r?   r    r2   r"   ÚstructÚunpackrF   r   )r   r=   rA   ÚbitsÚir   r   r   r?   O  s    ,zDerInteger._decodeFromStream)r   NN)F)r(   r)   r*   r+   r   r<   rB   r?   r   r   r   r   r     s
   

c               @   s4   e Zd ZdZddd„Zdd„ Zddd	„Zd
d„ ZdS )r	   aR  Class to model a DER-encoded BOOLEAN.

    An example of encoding is::

    >>> from Crypto.Util.asn1 import DerBoolean
    >>> bool_der = DerBoolean(True)
    >>> print(bool_der.encode().hex())

    which will show ``0101ff``, the DER encoding of True.

    And for decoding::

    >>> s = bytes.fromhex('0101ff')
    >>> try:
    >>>   bool_der = DerBoolean()
    >>>   bool_der.decode(s)
    >>>   print(bool_der.value)
    >>> except ValueError:
    >>>   print "Not a valid DER BOOLEAN"

    the output will be ``True``.

    :ivar value: The boolean value
    :vartype value: boolean
    FNc             C   s   t j| dd|d|ƒ || _dS )až  Initialize the DER object as a BOOLEAN.

        Args:
          value (boolean):
            The value of the boolean. Default is False.

          implicit (integer or byte):
            The IMPLICIT tag number (< 0x1F) to use for the encoded object.
            It overrides the universal tag for BOOLEAN (1).
            It cannot be combined with the ``explicit`` parameter.
            By default, there is no IMPLICIT tag.

          explicit (integer or byte):
            The EXPLICIT tag number (< 0x1F) to use for the encoded object.
            It cannot be combined with the ``implicit`` parameter.
            By default, there is no EXPLICIT tag.
        r&   r,   FN)r   r   rF   )r   rF   r4   r5   r   r   r   r   €  s    zDerBoolean.__init__c             C   s   | j r
dnd| _tj| ƒS )z9Return the DER BOOLEAN, fully encoded as a binary string.ó   ÿó    )rF   r2   r   r<   )r   r   r   r   r<   –  s    zDerBoolean.encodec             C   s   t j| ||ƒS )zßDecode a DER-encoded BOOLEAN, and re-initializes this object with it.

        Args:
            der_encoded (byte string): A DER-encoded BOOLEAN.

        Raises:
            ValueError: in case of parsing errors.
        )r   rB   )r   r@   rA   r   r   r   rB   œ  s    
zDerBoolean.decodec             C   sd   t j| ||ƒ t| jƒdkr$tdƒ‚t| jd ƒdkr>d| _n"t| jd ƒdkrXd| _ntdƒ‚dS )	z)Decode a DER-encoded BOOLEAN from a file.r&   z7Invalid encoding for DER BOOLEAN: payload is not 1 byter   FrG   TzInvalid payload for DER BOOLEANN)r   r?   r    r2   r"   r   rF   )r   r=   rA   r   r   r   r?   ¨  s    zDerBoolean._decodeFromStream)FNN)F)r(   r)   r*   r+   r   r<   rB   r?   r   r   r   r   r	   f  s
   

c               @   s˜   e Zd ZdZd%dd„Zdd„ Zdd„ Zd	d
„ Zdd„ Zdd„ Z	dd„ Z
dd„ Zdd„ Zdd„ Zdd„ Zd&dd„Zd'dd„Zdd„ Zd(d!d"„Zd#d$„ ZdS ))r   aÏ  Class 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'']

        Nc             C   s.   t j| dd|d|ƒ |dkr$g | _n|| _dS )aC  Initialize the DER object as a SEQUENCE.

                :Parameters:
                  startSeq : Python sequence
                    A sequence whose element are either integers or
                    other DER objects.

                  implicit : integer or byte
                    The IMPLICIT tag number (< 0x1F) to use for the encoded object.
                    It overrides the universal tag for SEQUENCE (16).
                    It cannot be combined with the ``explicit`` parameter.
                    By default, there is no IMPLICIT tag.

                  explicit : integer or byte
                    The EXPLICIT tag number (< 0x1F) to use for the encoded object.
                    It cannot be combined with the ``implicit`` parameter.
                    By default, there is no EXPLICIT tag.
                é   r,   TN)r   r   Ú_seq)r   ZstartSeqr4   r5   r   r   r   r   ä  s    zDerSequence.__init__c             C   s   | j |= d S )N)rS   )r   Únr   r   r   Ú__delitem__   s    zDerSequence.__delitem__c             C   s
   | j | S )N)rS   )r   rT   r   r   r   Ú__getitem__  s    zDerSequence.__getitem__c             C   s   || j |< d S )N)rS   )r   ÚkeyrF   r   r   r   Ú__setitem__  s    zDerSequence.__setitem__c             C   s   || j ||…< d S )N)rS   )r   rO   ÚjÚsequencer   r   r   Ú__setslice__	  s    zDerSequence.__setslice__c             C   s   | j ||…= d S )N)rS   )r   rO   rY   r   r   r   Ú__delslice__  s    zDerSequence.__delslice__c             C   s   | j td|ƒtd|ƒ… S )Nr   )rS   Úmax)r   rO   rY   r   r   r   Ú__getslice__  s    zDerSequence.__getslice__c             C   s
   t | jƒS )N)r    rS   )r   r   r   r   Ú__len__  s    zDerSequence.__len__c             C   s   | j j|ƒ | S )N)rS   Úappend)r   Úitemr   r   r   Ú__iadd__  s    zDerSequence.__iadd__c             C   s   | j j|ƒ | S )N)rS   r`   )r   ra   r   r   r   r`     s    zDerSequence.appendc             C   s   | j j||ƒ | S )N)rS   Úinsert)r   Úindexra   r   r   r   rc     s    zDerSequence.insertTc                s   ‡ fdd„| j D ƒ}t|ƒS )zìReturn the number of items in this sequence that are
                integers.

                Args:
                  only_non_negative (boolean):
                    If ``True``, negative integers are not counted in.
                c                s   g | ]}t |ˆ ƒr|‘qS r   )r   )Ú.0r   )r   r   r   ú
<listcomp>*  s    z'DerSequence.hasInts.<locals>.<listcomp>)rS   r    )r   r   Úitemsr   )r   r   ÚhasInts!  s    	zDerSequence.hasIntsc             C   s   | j o| j|ƒt| j ƒkS )a©  Return ``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``.)rS   rh   r    )r   r   r   r   r   ÚhasOnlyInts-  s    zDerSequence.hasOnlyIntsc             C   sj   d| _ xX| jD ]N}t|ƒr*|  j |7  _ qt|ƒrJ|  j t|ƒjƒ 7  _ q|  j |jƒ 7  _ qW tj| ƒS )zùReturn this DER SEQUENCE, fully encoded as a
                binary string.

                Raises:
                  ValueError: if some elements in the sequence are neither integers
                              nor byte strings.
                r,   )r2   rS   r   r   r   r<   r   )r   ra   r   r   r   r<   :  s    zDerSequence.encodeFc             C   s0   || _ tj| ||d�}|r,| jƒ  r,tdƒ‚|S )a9  Decode 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.
                )rA   zSome members are not INTEGERs)Ú_nr_elementsr   rB   ri   r"   )r   r@   rA   Znr_elementsZonly_ints_expectedr$   r   r   r   rB   L  s
    zDerSequence.decodec             C   sò   g | _ tj| ||ƒ t| jƒ}xp|jƒ dkrŽ|jƒ  tƒ }|j||ƒ |jdkrb| j j|j	ƒ ƒ q t
ƒ }|j	ƒ }|j||d� | j j|jƒ q W d}| jdk	rØyt| j ƒ| jk}W n$ tk
rÖ   t| j ƒ| jk}Y nX |sîtdt| j ƒ ƒ‚dS )z+Decode a complete DER SEQUENCE from a file.r   rE   )rA   TNz1Unexpected number of members (%d) in the sequence)rS   r   r?   r   r2   r!   r   r0   r`   r   r   rB   rF   rj   r    r   r"   )r   r=   rA   rC   ÚderÚderIntÚdataÚokr   r   r   r?   i  s,    


zDerSequence._decodeFromStream)NNN)T)T)FNF)r(   r)   r*   r+   r   rU   rV   rX   r[   r\   r^   r_   rb   r`   rc   rh   ri   r<   rB   r?   r   r   r   r   r   ¹  s"   )



c               @   s   e Zd ZdZddd„ZdS )r
   aâ  Class 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,   Nc             C   s   t j| d||dƒ dS )ah  Initialize 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).
        é   FN)r   r   )r   rF   r4   r   r   r   r   ¬  s    zDerOctetString.__init__)r,   N)r(   r)   r*   r+   r   r   r   r   r   r
   Ž  s   c               @   s   e Zd ZdZdd„ ZdS )r   z"Class to model a DER NULL element.c             C   s   t j| ddddƒ dS )z$Initialize the DER object as a NULL.é   r,   NF)r   r   )r   r   r   r   r   ¾  s    zDerNull.__init__N)r(   r)   r*   r+   r   r   r   r   r   r   »  s   c               @   s4   e Zd ZdZddd„Zdd„ Zdd	d
„Zdd„ ZdS )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
    Ú Nc             C   s   t j| dd|d|ƒ || _dS )a’  Initialize 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,   FN)r   r   rF   )r   rF   r4   r5   r   r   r   r   â  s    zDerObjectId.__init__c             C   sô   dd„ | j jdƒD ƒ}t|ƒdk r*tdƒ‚|d dkr>tdƒ‚|d dk r^|d d	kr^td
ƒ‚d|d  |d  g|dd…  }g }xJt|ƒD ]>}|j|d@ ƒ |dL }x"|rÊ|j|d@ dB ƒ |dL }qªW qŽW djdd„ t|ƒD ƒƒ| _tj	| ƒS )zCReturn the DER OBJECT ID, fully encoded as a
        binary string.c             S   s   g | ]}t |ƒ‘qS r   )rI   )re   r   r   r   r   rf   õ  s    z&DerObjectId.encode.<locals>.<listcomp>Ú.rE   z$Not a valid Object Identifier stringr   z!First component must be 0, 1 or 2r&   é'   z#Second component must be 39 at mosté(   Nr8   é   r.   r,   c             S   s   g | ]}t |ƒ‘qS r   )r   )re   r   r   r   r   rf     s    )
rF   Úsplitr    r"   Úreversedr`   Újoinr2   r   r<   )r   ÚcompsÚsubcompsr9   Úvr   r   r   r<   ñ  s"    "zDerObjectId.encodeFc             C   s   t j| ||ƒS )ab  Decode 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.
        )r   rB   )r   r@   rA   r   r   r   rB     s    zDerObjectId.decodec             C   sê   t j| ||ƒ t| jƒ}g }d}x:|jƒ rZ|jƒ }|d> |d@  }|d@ s"|j|ƒ d}q"W t|ƒdkrptdƒ‚|d dk r’d|d g|dd…< n>|d d	k r¸d|d d g|dd…< nd
|d d	 g|dd…< dj	dd„ |D ƒƒ| _
dS )z,Decode a complete DER OBJECT ID from a file.r   rv   r8   r.   zEmpty payloadru   Nr&   éP   rE   rs   c             S   s   g | ]}t |ƒ‘qS r   )Ústr)re   r   r   r   r   rf   7  s    z1DerObjectId._decodeFromStream.<locals>.<listcomp>)r   r?   r   r2   r!   r'   r`   r    r"   ry   rF   )r   r=   rA   rC   r{   r|   Úcr   r   r   r?     s$    


zDerObjectId._decodeFromStream)rq   NN)F)r(   r)   r*   r+   r   r<   rB   r?   r   r   r   r   r   Ä  s
   

c               @   s4   e Zd ZdZddd„Zdd„ Zdd	d
„Zdd„ ZdS )r   a¢  Class 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,   Nc             C   s4   t j| dd|d|ƒ t|t ƒr*|jƒ | _n|| _dS )aÉ  Initialize 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 BIT STRING (3).
          explicit : integer
            The EXPLICIT tag to use for the encoded object.
        é   r,   FN)r   r   Ú
isinstancer<   rF   )r   rF   r4   r5   r   r   r   r   W  s    
zDerBitString.__init__c             C   s   d| j  | _tj| ƒS )zBReturn the DER BIT STRING, fully encoded as a
        byte string.rQ   )rF   r2   r   r<   )r   r   r   r   r<   l  s    zDerBitString.encodeFc             C   s   t j| ||ƒS )aT  Decode 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.
        )r   rB   )r   r@   rA   r   r   r   rB   t  s    zDerBitString.decodec             C   sN   t j| ||ƒ | jr.t| jd ƒdkr.tdƒ‚d| _| jrJ| jdd… | _dS )z1Decode a complete DER BIT STRING DER from a file.r   zNot a valid BIT STRINGr,   r&   N)r   r?   r2   r   r"   rF   )r   r=   rA   r   r   r   r?   ƒ  s    zDerBitString._decodeFromStream)r,   NN)F)r(   r)   r*   r+   r   r<   rB   r?   r   r   r   r   r   :  s
   

c               @   sT   e Zd ZdZddd„Zdd„ Zdd„ Zd	d
„ Zdd„ Zddd„Z	dd„ Z
dd„ ZdS )r   a…  Class 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]``.
    Nc             C   s>   t j| dd|dƒ g | _d| _|r:x|D ]}| j|ƒ q(W dS )a9  Initialize 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)r   r   rS   Ú
_elemOctetÚadd)r   ZstartSetr4   Úer   r   r   r   ®  s    

zDerSetOf.__init__c             C   s
   | j | S )N)rS   )r   rT   r   r   r   rV   Ã  s    zDerSetOf.__getitem__c             C   s
   t | jƒS )N)ÚiterrS   )r   r   r   r   Ú__iter__Æ  s    zDerSetOf.__iter__c             C   s
   t | jƒS )N)r    rS   )r   r   r   r   r_   É  s    zDerSetOf.__len__c             C   sh   t |ƒrd}nt|tƒr | j}nt|d ƒ}| j|krN| jdk	rHtdƒ‚|| _|| jkrd| jj|ƒ dS )zâAdd 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.
        rE   r   Nz&New element does not belong to the set)	r   r�   r   r0   r   rƒ   r"   rS   r`   )r   ÚelemÚeor   r   r   r„   Ì  s    	



zDerSetOf.addFc             C   s   t j| ||ƒS )aÞ  Decode 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.
        )r   rB   )r   r@   rA   r   r   r   rB   ä  s    zDerSetOf.decodec             C   s²   g | _ tj| ||ƒ t| jƒ}d}xŠ|jƒ dkr¬|jƒ  tƒ }|j||ƒ |dk rZ|j}n||jkrltdƒ‚|dkr†| j j	|j
ƒ ƒ q$tƒ }|j|j
ƒ |ƒ | j j	|jƒ q$W dS )z)Decode a complete DER SET OF from a file.r&   r   z)Not all elements are of the same DER typerE   Néÿÿÿÿ)rS   r   r?   r   r2   r!   r   r0   r"   r`   r   r   rB   rF   )r   r=   rA   rC   Z
setIdOctetrk   rl   r   r   r   r?   ö  s"    

zDerSetOf._decodeFromStreamc             C   sj   g }xF| j D ]<}t|ƒr&t|ƒjƒ }nt|tƒr:|jƒ }n|}|j|ƒ qW |jƒ  dj|ƒ| _	tj| ƒS )zRReturn this SET OF DER element, fully encoded as a
        binary string.
        r,   )
rS   r   r   r<   r�   r   r`   Úsortry   r2   )r   Zorderedra   Zbysr   r   r   r<     s    

zDerSetOf.encode)NN)F)r(   r)   r*   r+   r   rV   r‡   r_   r„   rB   r?   r<   r   r   r   r   r   “  s   

!)F)rL   ZCrypto.Util.py3compatr   r   r   ZCrypto.Util.numberr   r   Ú__all__r   Úobjectr   r   r   r	   r   r
   r   r   r   r   r   r   r   r   Ú<module>   s"   

	  7_S V-	vY