
    ÿigm                     Z   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dS )    N)byte_stringbchrbord)long_to_bytesbytes_to_long)		DerObject
DerInteger
DerBooleanDerOctetStringDerNullDerSequenceDerObjectIdDerBitStringDerSetOfFc                 H    d}	 | |z   }n# t           $ r Y dS w xY w| p| dk    S )Nr   F)	TypeError)xonly_non_negativetests      P/var/www/html/afkarena/venv/lib/python3.11/site-packages/Cryptodome/Util/asn1.py
_is_numberr   (   sK    D4x   uu  *AF*s   
 
c                   6    e Zd ZdZd Zd Zd Zd Zd Zd Z	dS )	BytesIO_EOFzeThis class differs from BytesIO in that a ValueError exception is
    raised whenever EOF is reached.c                 0    || _         d| _        d | _        d S Nr   )_buffer_index	_bookmark)selfinitial_bytess     r   __init__zBytesIO_EOF.__init__5   s    $    c                     | j         | _        d S N)r   r   r   s    r   set_bookmarkzBytesIO_EOF.set_bookmark:   s    r"   c                 F    | j         J | j        | j         | j                 S r$   )r   r   r   r%   s    r   data_since_bookmarkzBytesIO_EOF.data_since_bookmark=   s&    ~)))|DN4;677r"   c                 :    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                  k    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   sy    K&(	s4<((((_clnqrvr~nn  cA  A  B  B  Bdk)34r"   c                 R    t          |                     d          d                   S )N   r   )r   r1   r%   s    r   	read_bytezBytesIO_EOF.read_byteM   s    DIIaLLO$$$r"   N)
__name__
__module____qualname____doc__r!   r&   r(   r+   r1   r4    r"   r   r   r   1   sx        ' '  
% % %8 8 8/ / /  % % % % %r"   r   c                   T    e Zd ZdZ	 	 ddZd Zed             Zd Zd	 Z	dd
Z
d ZdS )r   zpBase class for defining a single DER object.

        This class should never be directly instantiated.
        Nr"   Fc                 <   |	d| _         dS |                     |          }|| _        |rdnd}d||fvrt          d          |"d|z  |                     |          z  | _         dS |)d|                     |          z  | _         ||z  | _        dS ||z  | _         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   asn1IdrA   implicitconstructedexplicitconstructed_bits          r   r!   zDerObject.__init__W   s    > >&*DOF))&11&  +6"?$$4(333$ &; < < < '&*_&<t?O?OPX?Y?Y&YDOOO)&1D4D4DX4N4N&NDO,;f,DD))) '6&>DOOOr"   c                     t          |          s(t          |          dk    rt          |d                   }t          |          rd|cxk    rdk     sn 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   sg     "# +3xx1}}"3q6ll"3 6AOOOOtOOOO$_555
r"   c                     | dk    r1t          |           }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   sD    
 C<<#0#8#8#CMMC$7888CCF||#r"   c                 ,   | j         }t          | d          rDt          | j                  |                     t          | j                             z   | j         z   }t          | 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 4&*4+@&A&A&*&9&9#dl:K:K&L&L'M&*l'3N T_--++C,?,?@@A&' (r"   c                    |                                 }|dk    rd|                    |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   s     C<<%&VVFTM%:%:NN1-..!33()OPPP*>::F}}()`aaar"   c                     t          |          st          d          t          |          }|                     ||           |                                dk    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   st     #;// C$%ABBB,,&&q&111 ##%%))$%TUUUr"   c                 2   |                                 }| j        || j        k    rt          d          n|| _        |                     |          }|                    |          | _        t          | d          rt          | j                  }|                                 }|| j        k    rt          d          |                     |          }|                    |          | _        |	                                dk    rt          d          dS dS )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1()=>>> 2 '.DO++ vvf~~ 4!344 
Z#DL11A"#++--K"d&;;;()FGGG!__Q//F#$66&>>DL ''))A--()XYYY
Z 
Z .-r"   )Nr"   NFNF)r5   r6   r7   r8   r!   r@   staticmethodrN   rR   rV   r\   rY   r9   r"   r   r   r   Q   s        	 	
 ?C15D	? D	? D	? D	?L
	 
	 
	 
	$ 	$ 
	$	( 	( 	(&	 	 		 	 	 	.	Z 	Z 	Z 	Z 	Zr"   r   c                   .    e Zd ZdZd	dZd Zd
dZd ZdS )r	   a  Class to model a DER INTEGER.

        An example of encoding is::

          >>> from Cryptodome.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                 R    t                               | 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   rg   rD   rF   s       r   r!   zDerInteger.__init__#  s4     ""4sH#((4 4 4"


r"   c                 2   | 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  }ot                              |           S )zIReturn the DER INTEGER, fully encoded as a
                binary string.r"   T   r=   r   i   )rg   rA   r   intr   rR   )r   numbers     r   rR   zDerInteger.encode3  s     "!#'FSL(9(9#:#:T\#IDLf+++++++++'+DzzDL'@v,,,,,,,,,qLF! !''---r"   Fc                 <    t                               | ||          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IIr"   c                 0   t                               | ||           |rzt          | 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}| j        D ]4}| xj        d	z  c_        | xj        t          |          z  c_        |d
z  }5| j        r/t          | j        d                   dz  r| xj        |z  c_        dS dS 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 zeror3      rk   )	r   rY   r*   rA   r-   structunpackrg   r   )r   rT   r[   bitsis        r   rY   zDerInteger._decodeFromStreamO  s4    ++D!V<<< [4<((A--()Z[[[4<((A--&-dlSUTUSUFV2W2WXY2Z]a2a2a()YZZZ 
  AJJ#%JJJJ$q'')JJQJDD< 'Da$9$9D$@ 'JJ$&JJJJ' ' ' 'r"   )r   NNra   r5   r6   r7   r8   r!   rR   r\   rY   r9   r"   r   r	   r	     sh        	 	6	# 	# 	# 	# 	. 	. 	.	J 	J 	J 	J	' 	' 	' 	' 	'r"   r	   c                   .    e Zd ZdZddZd Zd	dZd ZdS )
r
   aV  Class to model a DER-encoded BOOLEAN.

    An example of encoding is::

    >>> from Cryptodome.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                 R    t                               | 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.
        r3   r"   FNrf   rh   s       r   r!   zDerBoolean.__init__  s-    & 	4sHeXFFF


r"   c                 V    | j         rdnd| _        t                              |           S )z9Return the DER BOOLEAN, fully encoded as a binary string.       rg   rA   r   rR   r%   s    r   rR   zDerBoolean.encode  s*     #'*9ww'%%%r"   c                 :    t                               | ||          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                 B   t                               | ||           t          | j                  dk    rt	          d          t          | j        d                   dk    r	d| _        dS t          | j        d                   dk    r	d| _        dS 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  s     	##D!V444t|!!VWWWQ  A%%DJJJ$,q/""d**DJJJ>???r"   )FNNra   rx   r9   r"   r   r
   r
   f  si         2   ,& & &
; 
; 
; 
;@ @ @ @ @r"   r
   c                   z    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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 Cryptodome.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                 h    t                               | dd|d|           |	g | _        dS || _        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   startSeqrD   rF   s       r   r!   zDerSequence.__init__  s>    ( ""4sHdHMMM# "DIII (DIIIr"   c                     | j         |= d S r$   r   r   ns     r   __delitem__zDerSequence.__delitem__   s    IaLLLr"   c                     | j         |         S r$   r   r   s     r   __getitem__zDerSequence.__getitem__  s    y|#r"   c                     || j         |<   d S r$   r   )r   keyrg   s      r   __setitem__zDerSequence.__setitem__  s    !&	#r"   c                     || j         ||<   d S r$   r   )r   rw   jsequences       r   __setslice__zDerSequence.__setslice__	  s    !)	!A#r"   c                     | j         ||= d S r$   r   r   rw   r   s      r   __delslice__zDerSequence.__delslice__  s    IacNNNr"   c                 X    | j         t          d|          t          d|                   S r   )r   maxr   s      r   __getslice__zDerSequence.__getslice__  s$    yQ3q!99!455r"   c                 *    t          | j                  S r$   r*   r   r%   s    r   __len__zDerSequence.__len__  s    49~~%r"   c                 :    | j                             |           | S r$   r   appendr   items     r   __iadd__zDerSequence.__iadd__      	  &&&r"   c                 :    | j                             |           | S r$   r   r   s     r   r   zDerSequence.append  r   r"   c                 <    | j                             ||           | S r$   )r   insert)r   indexr   s      r   r   zDerSequence.insert  s    	  ---r"   Tc                 H    fd| j         D             }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.
                c                 4    g | ]}t          |          |S r9   )r   ).0r   r   s     r   
<listcomp>z'DerSequence.hasInts.<locals>.<listcomp>*  s)    RRRqA?P1Q1QRRRRr"   )r   r*   )r   r   itemss    ` r   hasIntszDerSequence.hasInts!  s-     SRRRDIRRR5zz!r"   c                 f    | j         o*|                     |          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+     yVT\\2C%D%DDI%VVr"   c                 Z   d| _         | j        D ]}t          |          r| xj         |z  c_         "t          |          r0| xj         t	          |                                          z  c_         a| xj         |                                z  c_         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"   )rA   r   r   r   r	   rR   r   r   s     r   rR   zDerSequence.encode:  s      # I 6 6D"4(( 6,#D)) 6
4(8(8(?(?(A(AA5 ''---r"   Fc                     || _         t                              | ||          }|r#|                                 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  sW    * %0!"))$F)KK% Fd.>.>.@.@ F$%DEEEr"   c                 V   g | _         t                              | ||           t          | j                  }|                                dk    r|                                 t                      }|                    ||           |j        dk    r-| j                             |	                                           nXt                      }|	                                }|                    ||           | j                             |j                   |                                dk    d}| j        J	 t          | j                   | j        v }n-# t          $ r  t          | j                   | j        k    }Y nw xY w|s$t!          dt          | j                   z            dS )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  s    	 ++D!V<<<  --&&((1,,NN$$$#++C))!V444 ~--	(()>)>)@)@AAAA!+ 4466d6:::	((666 &&((1,, $0A ^^t/@@$ A A A ^^t/@@A  J$ &8:=di..&I J J JJ J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     s,       (	 (	T	) 	) 	) 	)8	! 	! 	!	$ 	$ 	$	' 	' 	'	* 	* 	*	# 	# 	#	6 	6 	6	& 	& 	&	 	 		 	 		 	 	
	" 
	" 
	" 
	"	W 	W 	W 	W	. 	. 	.$	 	 	 	:"	J "	J "	J "	J "	Jr"   r   c                       e Zd ZdZddZdS )r   a  Class to model a DER OCTET STRING.

    An example of encoding is:

    >>> from Cryptodome.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                 B    t                               | 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   rg   rD   s      r   r!   zDerOctetString.__init__  s&     	4uh>>>>>r"   )r"   Nr5   r6   r7   r8   r!   r9   r"   r   r   r     s2         :? ? ? ? ? ?r"   r   c                       e Zd ZdZd ZdS )r   z"Class to model a DER NULL element.c                 B    t                               | dddd           dS )z$Initialize the DER object as a NULL.   r"   NFr   r%   s    r   r!   zDerNull.__init__  s&     	4sD%88888r"   Nr   r9   r"   r   r   r     s)        ,,9 9 9 9 9r"   r   c                   .    e Zd ZdZd	dZd Zd
dZd ZdS )r   a,  Class to model a DER OBJECT ID.

    An example of encoding is:

    >>> from Cryptodome.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                 R    t                               | 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"   FNrf   rh   s       r   r!   zDerObjectId.__init__  s-     	4sHeXFFF


r"   c                    d | 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         z  |d         z   g|dd         z   }g }t	          |          D ]C}|                    |dz             |dz  }|r"|                    |dz  dz             |dz  }|"Dd                    d t	          |          D                       | _        t          	                    |           S )zCReturn the DER OBJECT ID, fully encoded as a
        binary string.c                 ,    g | ]}t          |          S r9   )rl   r   r   s     r   r   z&DerObjectId.encode.<locals>.<listcomp>  s    777AQ777r"   .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"   c                 ,    g | ]}t          |          S r9   )r   r   s     r   r   z&DerObjectId.encode.<locals>.<listcomp>  s     E E EQa E E Er"   )
rg   splitr*   r-   reversedr   joinrA   r   rR   )r   compssubcompsrM   vs        r   rR   zDerObjectId.encode  sa    87!1!1#!6!6777u::>>CDDD8a<<@AAA8a<<E!HrMMBCCCqME!H,-abb	9(## 	 	AOOAH%%%!GA TT 1222a   xx E E(82D2D E E EFF%%%r"   Fc                 :    t                               | ||          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                 Z   t                               | ||           t          | j                  }g }d}|                                rO|                                }|dz  |dz  z   }|dz  s|                    |           d}|                                Ot          |          dk    rt          d          |d         dk     rd|d         g|dd<   n1|d         d	k     rd|d         dz
  g|dd<   nd
|d         d	z
  g|dd<   d	                    d |D                       | _
        dS )z,Decode a complete DER OBJECT ID from a file.r   r   rL   r=   zEmpty payloadr   Nr3   P   re   r   c                 ,    g | ]}t          |          S r9   )strr   s     r   r   z1DerObjectId._decodeFromStream.<locals>.<listcomp>7  s    888!s1vv888r"   )r   rY   r   rA   r+   r4   r   r*   r-   r   rg   )r   rT   r[   r_   r   r   cs          r   rY   zDerObjectId._decodeFromStream  sX    	##D!V444 %%   	AaAH%AH """    	 x==A_---A;x{+HRaRLLa[2x{R/0HRaRLLx{R/0HRaRLXX88x88899


r"   )r   NNra   rx   r9   r"   r   r   r     sd         :   & & &4; ; ; ; : : : : :r"   r   c                   .    e Zd ZdZd	dZd Zd
dZd ZdS )r   a  Class to model a DER BIT STRING.

    An example of encoding is:

    >>> from Cryptodome.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                     t                               | dd|d|           t          |t                     r|                                | _        dS || _        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!   
isinstancerR   rg   rh   s       r   r!   zDerBitString.__init__W  sT     	4sHeXFFF eY'' 	DJJJDJJJr"   c                 T    d| j         z   | _        t                              |           S )zBReturn the DER BIT STRING, fully encoded as a
        byte string.r}   r~   r%   s    r   rR   zDerBitString.encodel  s&    
 +%%%r"   Fc                 :    t                               | ||          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        r-t          | j        d                   dk    rt	          d          d| _        | j        r| j        dd         | _        dS dS )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  s     	##D!V444< 	7Da11Q665666 
< 	*abb)DJJJ	* 	*r"   )r"   NNra   rx   r9   r"   r   r   r   :  sd         8   *& & &; ; ; ;* * * * *r"   r   c                   F    e Zd ZdZddZd Zd Zd Zd Zdd	Z	d
 Z
d ZdS )r   a  Class to model a DER SET OF.

    An example of encoding is:

    >>> from Cryptodome.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                               | dd|d           g | _        d| _        |r|D ]}|                     |           dS 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!   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    y|r"   c                 *    t          | j                  S r$   )iterr   r%   s    r   __iter__zDerSetOf.__iter__  s    DIr"   c                 *    t          | j                  S r$   r   r%   s    r   r   zDerSetOf.__len__  s    49~~r"   c                 (   t          |          rd}n2t          |t                    r| j        }nt	          |d                   }| j        |k    r| j        t          d          || _        || j        vr| j                            |           dS dS )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 	BBi(( 	BBd1gB?b  * !IJJJ DOty  IT""""" ! r"   Fc                 :    t                               | ||          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                    g | _         t                              | ||           t          | j                  }d}|                                dk    r|                                 t                      }|                    ||           |dk     r|j        }n||j        k    rt          d          |dk    r-| j         	                    |
                                           nUt                      }|                    |
                                |           | j         	                    |j                   |                                dk    dS dS )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  sI    	 	##D!V444 %%
  1$$NN++C!!!V,,, A~~ ^

//$%PQQQ T!!	  !6!6!8!89999#a3355v>>>	  ...'   1$$$$$$r"   c                    g }| j         D ]t}t          |          r"t          |                                          }n,t	          |t
                    r|                                }n|}|                    |           u|                                 d                    |          | _	        t
                              |           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     I 	  	 D$  &&--//D),, kkmmNN3xx((%%%r"   )NNra   )r5   r6   r7   r8   r!   r   r   r   r   r\   rY   rR   r9   r"   r   r   r     s         4   *      # # #0; ; ; ;$/ / /B& & & & &r"   r   ra   )rt   Cryptodome.Util.py3compatr   r   r   Cryptodome.Util.numberr   r   __all__r   objectr   r   r	   r
   r   r   r   r   r   r   r9   r"   r   <module>r      sv  .  = = = = = = = = = = ? ? ? ? ? ? ? ?P P P+ + + +% % % % %& % % %@sZ sZ sZ sZ sZ sZ sZ sZl\' \' \' \' \' \' \' \'~P@ P@ P@ P@ P@ P@ P@ P@fRJ RJ RJ RJ RJ) RJ RJ RJj*? *? *? *? *?Y *? *? *?Z9 9 9 9 9i 9 9 9s: s: s: s: s:) s: s: s:lV* V* V* V* V*9 V* V* V*rU& U& U& U& U&y U& U& U& U& U&r"   