
    ,hI                        d dl Z d dlmZmZmZ d dlmZmZ g dZddZ	 G d de
      Z G d d	e
      Z G d
 de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Zy)    N)byte_stringbchrbord)long_to_bytesbytes_to_long)		DerObject
DerInteger
DerBooleanDerOctetStringDerNullDerSequenceDerObjectIdDerBitStringDerSetOfc                 D    d}	 | |z   }| xs | dk\  S # t         $ r Y yw xY w)Nr   F)	TypeError)xonly_non_negativetests      R/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/Crypto/Util/asn1.py
_is_numberr   (   s=    D4x ! *AF*  s    	c                   4    e Zd ZdZd Zd Zd Zd Zd Zd Z	y)	BytesIO_EOFzeThis class differs from BytesIO in that a ValueError exception is
    raised whenever EOF is reached.c                 .    || _         d| _        d | _        y Nr   )_buffer_index	_bookmark)selfinitial_bytess     r   __init__zBytesIO_EOF.__init__5   s    $    c                 &    | j                   | _        y N)r   r   r   s    r   set_bookmarkzBytesIO_EOF.set_bookmark:   s    r"   c                 d    | j                   J | j                  | j                   | j                   S r$   )r   r   r   r%   s    r   data_since_bookmarkzBytesIO_EOF.data_since_bookmark=   s(    ~~))||DNN4;;77r"   c                 F    t        | j                        | j                  z
  S r$   )lenr   r   r%   s    r   remaining_datazBytesIO_EOF.remaining_dataA   s    4<< 4;;..r"   c                     | j                   |z   }|t        | j                        kD  r#t        d|t        | j                        fz        | j                  | j                   | }|| _         |S )Nz@Not enough data for DER decoding: expected %d bytes and found %d)r   r*   r   
ValueError)r   length	new_indexresults       r   readzBytesIO_EOF.readD   sr    KK&(	s4<<((_clnqrvr~r~n  cA  A  B  Bdkk)4r"   c                 <    t        | j                  d      d         S )N   r   )r   r1   r%   s    r   	read_bytezBytesIO_EOF.read_byteM   s    DIIaLO$$r"   N)
__name__
__module____qualname____doc__r!   r&   r(   r+   r1   r4    r"   r   r   r   1   s%    '
%8/%r"   r   c                   L    e Zd ZdZ	 	 d
dZd Zed        Zd Zd Z	ddZ
d	 Zy)r   zpBase class for defining a single DER object.

        This class should never be directly instantiated.
        Nc                    |d| _         y| j                  |      }|| _        |rdnd}d||fvrt        d      |d|z  | j                  |      z  | _         y|$d| j                  |      z  | _         ||z  | _        y||z  | _         y)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   asn1IdrA   implicitconstructedexplicitconstructed_bits          r   r!   zDerObject.__init__W   s    > >&*DO))&1&  +6$4(33$ &; < < '&*_&<t?O?OPX?Y&YDO)&1D4D4DX4N&NDO,;f,DD) '6&>DOr"   c                     t        |      st        |      dk(  rt        |d         }t        |      rd|cxk  rdk  st        d       t        d      |S )zCheck if *tag* is a real DER tag (5 bits).
                Convert it from a character to number if necessary.
                r3   r      zWrong DER tag)r   r*   r   r-   )r   tags     r   r@   zDerObject._convertTag   sT     "#3x1}"3q6l"3AOtO$_55 -<$_55
r"   c                 l    | dkD  r%t        |       }t        t        |      dz         |z   S t        |       S )zXBuild length octets according to BER/DER
                definite form.
                   r=   )r   r   r*   )r.   encodings     r   _definite_formzDerObject._definite_form   s8    
 C<#0#8#CMC$788CCF|#r"   c                 &   | j                   }t        | d      rGt        | j                        | j	                  t        | j                               z   | j                   z   }t        | j                        | j	                  t        |            z   |z   S )z?Return this DER element, fully encoded as a binary byte string.rB   )rA   hasattrr   rB   rN   r*   r?   )r   output_payloads     r   encodezDerObject.encode   s     "& 4!34&*4+@+@&A&*&9&9#dll:K&L'M&*ll'3N T__-++C,?@A&' (r"   c                     |j                         }|dkD  rK|j                  |dz        }t        |d         dk(  rt        d      t	        |      }|dk  rt        d      |S )z%Decode DER length octets from a file.rL   r   z$Invalid DER: length has leading zeroz5Invalid DER: length in long form but smaller than 128)r4   r1   r   r-   r   )r   sr.   encoded_lengths       r   
_decodeLenzDerObject._decodeLen   sh     C<%&VVFTM%:NN1-.!3()OPP*>:F}()`aar"   c                     t        |      st        d      t        |      }| j                  ||       |j	                         dkD  rt        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   -Unexpected extra data after the DER structure)r   r-   r   _decodeFromStreamr+   )r   der_encodedstrictrT   s       r   decodezDerObject.decode   sV     #;/$%ABB,&&q&1 ##%)$%TUUr"   c                    |j                         }| j                  || j                  k7  rt        d      || _        | j                  |      }|j	                  |      | _        t        | d      rt        | j
                        }|j                         }|| j                  k7  rt        d      | j                  |      }|j	                  |      | _        |j                         dkD  rt        d      yy)z*Decode a complete DER element from a file.NzUnexpected DER tagrB   zUnexpected internal DER tagr   rX   )
r4   r?   r-   rV   r1   rA   rP   r   rB   r+   )r   rT   r[   idOctetr.   pinner_octets          r   rY   zDerObject._decodeFromStream   s     ++-??.$//1()=>>&-DO+ vvf~ 4!34#DLL1A"#++-K"d&;&;;()FGG!__Q/F#$66&>DL '')A-()XYY . 5r"   )Nr"   NFNF)r5   r6   r7   r8   r!   r@   staticmethodrN   rR   rV   r\   rY   r9   r"   r   r   r   Q   sE    	
 ?C15D	?L
	 
	$ 
	$	(&		.	Zr"   r   c                   ,    e Zd ZdZddZd ZddZd Zy)	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
        Nc                 F    t         j                  | dd|d|       || _        y)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   rg   rD   rF   s       r   r!   zDerInteger.__init__#  s&     ""4sH#((4"
r"   c                 &   | j                   }d| _        	 t        t        |dz              | j                  z   | _        d|cxk  rdk  r n nt        d      | j                  z   | _        d|cxk  rdk  rn nn|dz  }it        j                  |       S )zIReturn the DER INTEGER, fully encoded as a
                binary string.r"      r=   r   i   )rg   rA   r   intr   rR   )r   numbers     r   rR   zDerInteger.encode3  s     "#'FSL(9#:T\\#IDLf++'+DzDLL'@v,,qLF  !''--r"   c                 2    t         j                  | ||      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.
                r[   r   r\   r   rZ   r[   s      r   r\   zDerInteger.decodeB  s     !''k&'IIr"   c                 4   t         j                  | ||       |rot        | j                        dk(  rt	        d      t        | j                        dk\  r4t        j                  d| j                  dd       d   dk  rt	        d      d| _        d}| j                  D ]:  }| xj                  d	z  c_        | xj                  t        |      z  c_        |d
z  }< | j                  r2t        | j                  d         dz  r| xj                  |z  c_        yyy)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 zeror3      rk   )	r   rY   r*   rA   r-   structunpackrg   r   )r   rT   r[   bitsis        r   rY   zDerInteger._decodeFromStreamO  s     ++D!V<4<<(A-()Z[[4<<(A-&--dllSUTUFV2WXY2Z]a2a()YZZ 
 AJJ#%JJJ$q')JQJD <<Da$9D$@JJ$&J %A<r"   )r   NNra   r5   r6   r7   r8   r!   rR   r\   rY   r9   r"   r   r	   r	     s    	6	# 	.	J	'r"   r	   c                   ,    e Zd ZdZddZd ZddZd Zy)	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
    Nc                 F    t         j                  | dd|d|       || _        y)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.
        r3   r"   FNrf   rh   s       r   r!   zDerBoolean.__init__  s#    & 	4sHeXF
r"   c                 V    | j                   rdnd| _        t        j                  |       S )z9Return the DER BOOLEAN, fully encoded as a binary string.       rg   rA   r   rR   r%   s    r   rR   zDerBoolean.encode  s$     #'**w'%%r"   c                 0    t         j                  | ||      S )zDecode 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.
        rp   rq   s      r   r\   zDerBoolean.decode  s     k6::r"   c                    t         j                  | ||       t        | j                        dk7  rt	        d      t        | j                  d         dk(  rd| _        yt        | j                  d         dk(  rd| _        yt	        d      )	z)Decode a DER-encoded BOOLEAN from a file.r3   z7Invalid encoding for DER BOOLEAN: payload is not 1 byter   Frj   TzInvalid payload for DER BOOLEANN)r   rY   r*   rA   r-   r   rg   r   rT   r[   s      r   rY   zDerBoolean._decodeFromStream  sw     	##D!V4t||!VWWQ A%DJ$,,q/"d*DJ>??r"   )FNNra   rx   r9   r"   r   r
   r
   f  s    2,&
;@r"   r
   c                   x    e Zd ZdZddZd Zd Zd Zd Zd Z	d	 Z
d
 Zd Zd Zd ZddZddZd ZddZd Zy)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                 Z    t         j                  | dd|d|       |g | _        y|| _        y)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   startSeqrD   rF   s       r   r!   zDerSequence.__init__  s0    ( ""4sHdHM# "DI (DIr"   c                     | j                   |= y r$   r   r   ns     r   __delitem__zDerSequence.__delitem__   s    IIaLr"   c                      | j                   |   S r$   r   r   s     r   __getitem__zDerSequence.__getitem__  s    yy|#r"   c                 "    || j                   |<   y r$   r   )r   keyrg   s      r   __setitem__zDerSequence.__setitem__  s    !&		#r"   c                 "    || j                   || y r$   r   )r   rw   jsequences       r   __setslice__zDerSequence.__setslice__	  s    !)		!Ar"   c                 "    | j                   ||= y r$   r   r   rw   r   s      r   __delslice__zDerSequence.__delslice__  s    IIacNr"   c                 H    | j                   t        d|      t        d|       S r   )r   maxr   s      r   __getslice__zDerSequence.__getslice__  s    yyQ3q!955r"   c                 ,    t        | j                        S r$   r*   r   r%   s    r   __len__zDerSequence.__len__  s    499~%r"   c                 <    | j                   j                  |       | S r$   r   appendr   items     r   __iadd__zDerSequence.__iadd__      		  &r"   c                 <    | j                   j                  |       | S r$   r   r   s     r   r   zDerSequence.append  r   r"   c                 >    | j                   j                  ||       | S r$   )r   insert)r   indexr   s      r   r   zDerSequence.insert  s    		  -r"   c                 n    | j                   D cg c]  }t        ||      s| }}t        |      S c c}w )zReturn the number of items in this sequence that are
                integers.

                Args:
                  only_non_negative (boolean):
                    If ``True``, negative integers are not counted in.
                )r   r   r*   )r   r   r   itemss       r   hasIntszDerSequence.hasInts!  s5     %)IIRqA?P1QRR5z! Ss   22c                 l    | j                   xr' | 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``.)r   r   r*   )r   r   s     r   hasOnlyIntszDerSequence.hasOnlyInts-  s*     yyVT\\2C%DDII%VVr"   c                 T   d| _         | j                  D ]~  }t        |      r| xj                   |z  c_         $t        |      r-| xj                   t	        |      j                         z  c_         \| xj                   |j                         z  c_          t        j                  |       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"   )rA   r   r   r   r	   rR   r   r   s     r   rR   zDerSequence.encode:  s      # II 6D"4(,#D)
4(8(?(?(AA56 !''--r"   c                 ~    || _         t        j                  | ||      }|r| j                         s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.
                ro   zSome members are not INTEGERs)_nr_elementsr   r\   r   r-   )r   rZ   r[   nr_elementsonly_ints_expectedr0   s         r   r\   zDerSequence.decodeL  sB    * %0!"))$F)K%d.>.>.@$%DEEr"   c                 .   g | _         t        j                  | ||       t        | j                        }|j                         dkD  r|j                          t               }|j                  ||       |j                  dk7  r*| j                   j                  |j                                nRt               }|j                         }|j                  ||       | j                   j                  |j                         |j                         dkD  rd}| j                  "	 t        | j                         | j                  v }|s!t!        dt        | j                         z        y# t        $ r% t        | j                         | j                  k(  }Y Qw xY w)z+Decode a complete DER SEQUENCE from a file.r   re   ro   TNz1Unexpected number of members (%d) in the sequence)r   r   rY   r   rA   r+   r&   r?   r   r(   r	   r\   rg   r   r*   r   r-   )r   rT   r[   r_   derderIntdataoks           r   rY   zDerSequence._decodeFromStreami  sc    	 ++D!V<  -&&(1,NN$#+C))!V4 ~~-		(()>)>)@A!+ 446d6:		((6 &&(1, $$0A ^t/@/@@ $ &8:=dii.&I J J  % A ^t/@/@@As   !!E& &+FF)NNN)T)FNF)r5   r6   r7   r8   r!   r   r   r   r   r   r   r   r   r   r   r   r   rR   r\   rY   r9   r"   r   r   r     sZ    (	T	)8	!	$	'	*	#	6	&			
	"	W	.$	:"	Jr"   r   c                       e Zd ZdZddZy)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
    Nc                 6    t         j                  | d||d       y)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   rg   rD   s      r   r!   zDerOctetString.__init__  s     	4uh>r"   )r"   Nr5   r6   r7   r8   r!   r9   r"   r   r   r     s    :?r"   r   c                       e Zd ZdZd Zy)r   z"Class to model a DER NULL element.c                 6    t         j                  | dddd       y)z$Initialize the DER object as a NULL.   r"   NFr   r%   s    r   r!   zDerNull.__init__  s     	4sD%8r"   Nr   r9   r"   r   r   r     s
    ,9r"   r   c                   ,    e Zd ZdZddZd ZddZd Zy)	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                 F    t         j                  | dd|d|       || _        y)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"   FNrf   rh   s       r   r!   zDerObjectId.__init__  s#     	4sHeXF
r"   c                 `   | j                   j                  d      D cg c]  }t        |       }}t        |      dk  rt	        d      |d   dkD  rt	        d      |d   dk  r|d   dkD  rt	        d      d	|d   z  |d   z   g|dd
 z   }g }t        |      D ]=  }|j                  |dz         |dz  }|s|j                  |dz  dz         |dz  }|r? dj                  t        |      D cg c]  }t        |       c}      | _	        t        j                  |       S c c}w c c}w )zCReturn the DER OBJECT ID, fully encoded as a
        binary string..re   z$Not a valid Object Identifier stringr   z!First component must be 0, 1 or 2r3   '   z#Second component must be 39 at most(   NrL      r=   r"   )rg   splitrl   r*   r-   reversedr   joinr   rA   r   rR   )r   r   compssubcompsrM   vs         r   rR   zDerObjectId.encode  s7    "&!1!1#!67AQ77u:>CDD8a<@AA8a<E!HrMBCCqME!H,-ab	9(# 	AOOAH%!GATT 12a 	 xx(82D EQa EF%%) 8& !Fs   D&3D+c                 0    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.
        rp   rq   s      r   r\   zDerObjectId.decode  s     k6::r"   c                    t         j                  | ||       t        | j                        }g }d}|j	                         rD|j                         }|dz  |dz  z   }|dz  s|j                  |       d}|j	                         rDt        |      dk(  rt        d      |d   dk  rd|d   g|dd n#|d   d	k  rd|d   dz
  g|dd nd
|d   d	z
  g|dd dj                  |D cg c]  }t        |       c}      | _        yc c}w )z,Decode a complete DER OBJECT ID from a file.r   r   rL   r=   zEmpty payloadr   Nr3   P   re   r   )r   rY   r   rA   r+   r4   r   r*   r-   r   strrg   )r   rT   r[   r_   r   r   cr   s           r   rY   zDerObjectId._decodeFromStream  s    	##D!V4 % AaAH%AH"   x=A_--A;x{+HRaLa[2x{R/0HRaLx{R/0HRaLXXx8!s1v89
8s   #D) NNra   rx   r9   r"   r   r   r     s    :&4; :r"   r   c                   ,    e Zd ZdZddZd ZddZd Zy)	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
    Nc                     t         j                  | dd|d|       t        |t               r|j                         | _        y|| _        y)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!   
isinstancerR   rg   rh   s       r   r!   zDerBitString.__init__W  s<     	4sHeXF eY'DJDJr"   c                 T    d| j                   z   | _        t        j                  |       S )zBReturn the DER BIT STRING, fully encoded as a
        byte string.r}   r~   r%   s    r   rR   zDerBitString.encodel  s%    
 +%%r"   c                 0    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.
        rp   rq   s      r   r\   zDerBitString.decodet  s     k6::r"   c                     t         j                  | ||       | j                  r&t        | j                  d         dk7  rt	        d      d| _        | j                  r| j                  dd | _        yy)z1Decode a complete DER BIT STRING DER from a file.r   zNot a valid BIT STRINGr"   r3   N)r   rY   rA   r   r-   rg   r   s      r   rY   zDerBitString._decodeFromStream  sd     	##D!V4<<Da1Q6566 
<<ab)DJ r"   )r"   NNra   rx   r9   r"   r   r   r   :  s    8*&;*r"   r   c                   D    e Zd ZdZddZd Zd Zd Zd ZddZ	d	 Z
d
 Zy)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                     t         j                  | dd|d       g | _        d| _        |r|D ]  }| j	                  |        yy)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!   r   
_elemOctetadd)r   startSetrD   es       r   r!   zDerSetOf.__init__  sL     	4sHd;	   r"   c                      | j                   |   S r$   r   r   s     r   r   zDerSetOf.__getitem__  s    yy|r"   c                 ,    t        | j                        S r$   )iterr   r%   s    r   __iter__zDerSetOf.__iter__  s    DIIr"   c                 ,    t        | j                        S r$   r   r%   s    r   r   zDerSetOf.__len__  s    499~r"   c                 $   t        |      rd}n+t        |t              r| j                  }nt	        |d         }| j
                  |k7  r| j
                  t        d      || _        || j                  vr| j                  j                  |       yy)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.
        re   r   Nz&New element does not belong to the set)	r   r   r   r?   r   r   r-   r   r   )r   elemeos      r   r   zDerSetOf.add  s}     dBi(Bd1gB??b * !IJJ DOtyy IIT" !r"   c                 0    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.
        rp   rq   s      r   r\   zDerSetOf.decode  s      k6::r"   c                 j   g | _         t        j                  | ||       t        | j                        }d}|j                         dkD  r|j                          t               }|j                  ||       |dk  r|j                  }n||j                  k7  rt        d      |dk7  r*| j                   j                  |j                                nOt               }|j                  |j                         |       | j                   j                  |j                         |j                         dkD  ryy)z)Decode a complete DER SET OF from a file.r   z)Not all elements are of the same DER typere   N)r   r   rY   r   rA   r+   r&   r?   r-   r   r(   r	   r\   rg   )r   rT   r[   r_   
setIdOctetr   r   s          r   rY   zDerSetOf._decodeFromStream  s     	 	##D!V4 %
 1$NN+C!!!V, A~ ^^
/$%PQQ T!		  !6!6!89#a335v>		  .'  1$r"   c                 P   g }| j                   D ][  }t        |      rt        |      j                         }n#t	        |t
              r|j                         }n|}|j                  |       ] |j                          dj                  |      | _	        t
        j                  |       S )zRReturn this SET OF DER element, fully encoded as a
        binary string.
        r"   )
r   r   r	   rR   r   r   r   sortr   rA   )r   orderedr   byss       r   rR   zDerSetOf.encode  s     II 	 D$ &--/D),kkmNN3	  	xx(%%r"   )NNra   )r5   r6   r7   r8   r!   r   r   r   r   r\   rY   rR   r9   r"   r   r   r     s0    4*#0;$/B&r"   r   ra   )rt   Crypto.Util.py3compatr   r   r   Crypto.Util.numberr   r   __all__r   objectr   r   r	   r
   r   r   r   r   r   r   r9   r"   r   <module>r      s   .  9 9 ;P+%& %@sZ sZl\' \'~P@ P@fRJ) RJj*?Y *?Z9i 9s:) s:lV*9 V*rU&y U&r"   