
    ,ha                         d Z dgZddlZddlmZ ddlmZmZmZ ddl	m
Z
 ddlmZ ddlmZ dd	lmZ dd
lmZ d Z eddd      Z G d de      Z G d de      Zd Zy)z"
Counter with CBC-MAC (CCM) mode.
CcmMode    N)	unhexlify)byte_stringbord_copy_bytes)is_writeable_buffer)strxor)long_to_bytes)BLAKE2s)get_random_bytesc                      t        dd|       S )NEnum )type)enumss    Y/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/Crypto/Cipher/_mode_ccm.pyenumr   3   s    E""          )NOT_STARTEDPROCESSING_AUTH_DATAPROCESSING_PLAINTEXTc                       e Zd Zy)CCMMessageTooLongErrorN)__name__
__module____qualname__r   r   r   r   r   9   s    r   r   c                   n    e Zd ZdZd Zd Zd Zd ZddZddZ	dd	Z
d
 Zd Zd Zd Zd ZddZddZy)r   a   Counter with CBC-MAC (CCM).

    This is an Authenticated Encryption with Associated Data (`AEAD`_) mode.
    It provides both confidentiality and authenticity.

    The header of the message may be left in the clear, if needed, and it will
    still be subject to authentication. The decryption step tells the receiver
    if the message comes from a source that really knowns the secret key.
    Additionally, decryption detects if any part of the message - including the
    header - has been modified or corrupted.

    This mode requires a nonce. The nonce shall never repeat for two
    different messages encrypted with the same key, but it does not need
    to be random.
    Note that there is a trade-off between the size of the nonce and the
    maximum size of a single message you can encrypt.

    It is important to use a large nonce if the key is reused across several
    messages and the nonce is chosen randomly.

    It is acceptable to us a short nonce if the key is only used a few times or
    if the nonce is taken from a counter.

    The following table shows the trade-off when the nonce is chosen at
    random. The column on the left shows how many messages it takes
    for the keystream to repeat **on average**. In practice, you will want to
    stop using the key way before that.

    +--------------------+---------------+-------------------+
    | Avg. # of messages |    nonce      |     Max. message  |
    | before keystream   |    size       |     size          |
    | repeats            |    (bytes)    |     (bytes)       |
    +====================+===============+===================+
    |       2^52         |      13       |        64K        |
    +--------------------+---------------+-------------------+
    |       2^48         |      12       |        16M        |
    +--------------------+---------------+-------------------+
    |       2^44         |      11       |         4G        |
    +--------------------+---------------+-------------------+
    |       2^40         |      10       |         1T        |
    +--------------------+---------------+-------------------+
    |       2^36         |       9       |        64P        |
    +--------------------+---------------+-------------------+
    |       2^32         |       8       |        16E        |
    +--------------------+---------------+-------------------+

    This mode is only available for ciphers that operate on 128 bits blocks
    (e.g. AES but not TDES).

    See `NIST SP800-38C`_ or RFC3610_.

    .. _`NIST SP800-38C`: http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C.pdf
    .. _RFC3610: https://tools.ietf.org/html/rfc3610
    .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html

    :undocumented: __init__
    c           	         |j                   | _         	 t        d d |      | _        	 || _        t        d d |      | _        || _        || _        || _        || _        d | _	        | j                   dk7  rt        d      |dvrt        d|z        dt        |      cxk  rdk  st        d       t        d      dt        |      z
  }|r.t        t        |            |kD  rt        d	t        |      z         | j                  j                  ||j                  fd
di|| _        t"        j$                  | _        d | _        g d| _        d| _        d| _        g | _         | j                  j                  || j                  j2                  fdt5        j6                  d|dz
        | j                  z   i|| _        | j8                  j;                  d      | _        d ||fvr| j?                          y y )N   zFCCM mode is only available for ciphers that operate on 128 bits blocks)         
         r!   z@Parameter 'mac_len' must be even and in the range 4..16 (not %d)      z<Length of parameter 'nonce' must be in the range 7..13 bytes   $Message too long for a %u-byte nonceivs                   updateencryptdecryptdigestverifyr   nonceBr   ) 
block_sizer   r3   _factory_key_mac_len_msg_len
_assoc_len_cipher_params_mac_tag
ValueErrorlenr
   r   newMODE_CBC_mac	MacStatusr   _mac_status_t_next_cumul_assoc_len_cumul_msg_len_cacheMODE_CTRstructpack_cipherr/   _s_0
_start_mac)	selffactorykeyr3   mac_lenmsg_len	assoc_lencipher_paramsqs	            r   __init__zCcmMode.__init__x   s    ",,@ tU3
5dC0	#+??b  @ A A 33 @BIJ K K SZ%2% 9 : : & 9 : : UOs=12Q6()ORUV[R\)\]] &DMM%%c&-&6&67)57 )67	 %00*
 !"
  )t}}(()-)?)?:/5{{3A/F/S: ,9: LL((6	 	7++OO ,r   c                 b   | j                   t        j                  k(  sJ d | j                  | j                  fvsJ t        | j                  t              sJ dt        | j                        z
  }| j                  dkD  dz  }|| j                  dz
  dz  dz  z  }||dz
  z  }t        j                  d|      | j                  z   t        | j                  |      z   }d}| j                  dkD  rC| j                  d	k  rd}n| j                  d
k  rd}d}nd}d}|t        | j                  |      z  }| j                  j                  d|       | j                  j                  d|       dj                  | j                        }d| _        t        j                   | _         | j#                  |       y )Nr*   r   r#   r      r   r4   r   i   l        s   r"   s   r$   )rC   rB   r   r:   r9   
isinstancerH   listr>   r3   r8   rJ   rK   r
   insertjoinr   _update)rO   rV   flagsb_0assoc_len_encodedenc_sizefirst_data_to_macs          r   rN   zCcmMode._start_mac   s}   9#8#889DOOT]];;<$++t,- TZZ 1$*4==1$*q00Qkk#u%

2]4==RS5TT  ??Q"23G,$/!$/!t!II 	1c"1/0  HHT[[1$99&'r   c                    | j                   t        j                  k7  sJ t        | j                        | j
                  k  sJ t        | j                        }|dkD  r"| j                  d| j
                  |z
  z         y y )Nr       )rC   rB   r   r>   rH   r5   r^   )rO   	len_caches     r   _pad_cache_and_updatezCcmMode._pad_cache_and_update   sg    9#8#8894;;$//12
 $	q=LLDOOi$?@A r   c                    d| j                   vrt        d      g d| _         | xj                  t        |      z  c_        | j                  $| j                  | j                  kD  rt        d      | j                  |       | S )ax  Protect associated data

        If there is any associated data, the caller has to invoke
        this function one or more times, before using
        ``decrypt`` or ``encrypt``.

        By *associated data* it is meant any data (e.g. packet headers) that
        will not be encrypted and will be transmitted in the clear.
        However, the receiver is still able to detect any modification to it.
        In CCM, the *associated data* is also called
        *additional authenticated data* (AAD).

        If there is no associated data, this method must not be called.

        The caller may split associated data in segments of any size, and
        invoke this method multiple times, each time with the next segment.

        :Parameters:
          assoc_data : bytes/bytearray/memoryview
            A piece of associated data. There are no restrictions on its size.
        r.   z<update() can only be called immediately after initializationr-   zAssociated data is too long)rE   	TypeErrorrF   r>   r:   r=   r^   )rO   
assoc_datas     r   r.   zCcmMode.update   s~    . 4::% @ A A*
 	Z0??&  4??2:;;Z r   c                 P   | j                   t        j                  k(  r4t        |      rt	        dd|      }| j
                  j                  |       yt        | j
                        | j                  k  sJ t        | j
                        dkD  rt        | j                  t        | j
                        z
  t        |            }| xj
                  t	        d||      z  c_        t	        |d|      }t        | j
                        | j                  k  ry| j                  j                  | j
                        | _        d| _        t        |      | j                  z  | j                  z  }t	        |d|      | _        |dkD  r'| j                  j                  |d|       dd | _        yy)zPUpdate the MAC with associated data or plaintext
           (without FSM checks)Nr   r   i)rC   rB   r   r   r   rH   appendr>   r5   minrA   r/   rD   )rO   assoc_data_ptfiller
update_lens       r   r^   zCcmMode._update  sN    y444"=1 +D$ FKK}-4;;$//12t{{a3t{{+;;]+-FKK;tV]CCK'mDM4;;$//1 ii''4DGDK'4??:T__L
!*dMB>ii''kz(BCCDIDG r   Nc                    d| j                   vrt        d      ddg| _         | j                  jt        | j                  t
              sJ t        | j                  D cg c]  }t        |       c}      | _        | j                  5| j                          n$| j                  | j                  k  rt        d      | j                  dt        | j                        z
  }t        t        t        |                  |kD  r!t        dt        | j                        z        t        |      | _        | j                          dg| _         | xj                  t        |      z  c_        | j                  | j                  kD  rt        d      | j                   t"        j$                  k(  r%| j'                          t"        j(                  | _        | j+                  |       | j,                  j/                  ||      S c c}w )	ab  Encrypt data with the key set at initialization.

        A cipher object is stateful: once you have encrypted a message
        you cannot encrypt (or decrypt) another message using the same
        object.

        This method can be called only **once** if ``msg_len`` was
        not passed at initialization.

        If ``msg_len`` was given, the data to encrypt can be broken
        up in two or more pieces and `encrypt` can be called
        multiple times.

        That is, the statement:

            >>> c.encrypt(a) + c.encrypt(b)

        is equivalent to:

             >>> c.encrypt(a+b)

        This function does not add any padding to the plaintext.

        :Parameters:
          plaintext : bytes/bytearray/memoryview
            The piece of data to encrypt.
            It can be of any length.
        :Keywords:
          output : bytearray/memoryview
            The location where the ciphertext must be written to.
            If ``None``, the ciphertext is returned.
        :Return:
          If ``output`` is ``None``, the ciphertext as ``bytes``.
          Otherwise, ``None``.
        r/   z@encrypt() can only be called after initialization or an update()r1   Associated data is too shortr*   r+   Message is too longoutput)rE   ri   r:   rZ   rH   r[   sumr>   r9   rN   rF   r=   r3   r
   r   rG   rC   rB   r   rg   r   r^   rL   r/   )rO   	plaintextru   xrV   s        r   r/   zCcmMode.encrypt7  s   J DJJ& = > >*
 ??"dkk401!4;;"?a3q6"?@DO}}(!$$t6 !?@@ == S_$A=Y01A5,-SVYZ^ZdZdVe-eff	NDMOO"DJs9~-.233y=== &&((==DY||##If#=== #@s   G<c                 0   d| j                   vrt        d      ddg| _         | j                  jt        | j                  t
              sJ t        | j                  D cg c]  }t        |       c}      | _        | j                  5| j                          n$| j                  | j                  k  rt        d      | j                  dt        | j                        z
  }t        t        t        |                  |kD  r!t        dt        | j                        z        t        |      | _        | j                          dg| _         | xj                  t        |      z  c_        | j                  | j                  kD  rt        d      | j                   t"        j$                  k(  r%| j'                          t"        j(                  | _        | j*                  j-                  ||      }|| j/                  |       |S | j/                  |       |S c c}w )	ad  Decrypt data with the key set at initialization.

        A cipher object is stateful: once you have decrypted a message
        you cannot decrypt (or encrypt) another message with the same
        object.

        This method can be called only **once** if ``msg_len`` was
        not passed at initialization.

        If ``msg_len`` was given, the data to decrypt can be
        broken up in two or more pieces and `decrypt` can be
        called multiple times.

        That is, the statement:

            >>> c.decrypt(a) + c.decrypt(b)

        is equivalent to:

             >>> c.decrypt(a+b)

        This function does not remove any padding from the plaintext.

        :Parameters:
          ciphertext : bytes/bytearray/memoryview
            The piece of data to decrypt.
            It can be of any length.
        :Keywords:
          output : bytearray/memoryview
            The location where the plaintext must be written to.
            If ``None``, the plaintext is returned.
        :Return:
          If ``output`` is ``None``, the plaintext as ``bytes``.
          Otherwise, ``None``.
        r0   z@decrypt() can only be called after initialization or an update()r2   rr   r*   r+   rs   rt   )rE   ri   r:   rZ   rH   r[   rv   r>   r9   rN   rF   r=   r3   r
   r   rG   rC   rB   r   rg   r   rL   r/   r^   )rO   
ciphertextru   rx   rV   rw   s         r   r0   zCcmMode.decrypt  s   J DJJ& C D D*
 ??"dkk401!4;;"?a3q6"?@DO}}(!$$t6 !?@@ == S_$A=Z12Q6,-SVYZ^ZdZdVe-eff
ODMOO"DJs:..233y=== &&((==D LL((F(C	>LL#  LL G #@s   Hc                 d    d| j                   vrt        d      dg| _         | j                         S )zCompute the *binary* MAC tag.

        The caller invokes this function at the very end.

        This method returns the MAC that shall be sent to the receiver,
        together with the ciphertext.

        :Return: the MAC, as a byte string.
        r1   zAdigest() cannot be called when decrypting or validating a message)rE   ri   _digest)rO   s    r   r1   zCcmMode.digest  s7     4::% 7 8 8Z
||~r   c                    | j                   r| j                   S | j                  jt        | j                  t              sJ t        | j                  D cg c]  }t        |       c}      | _        | j                  5| j                          n$| j                  | j                  k  rt        d      | j                  d| _        | j                          | j                  | j                  k7  rt        d      | j                          t        | j                  | j                        d | j                    | _         | j                   S c c}w )Nrr   r   zMessage is too short)r<   r:   rZ   rH   r[   rv   r>   r9   rN   rF   r=   rG   rg   r	   rD   rM   r8   rO   rx   s     r   r|   zCcmMode._digest  s    ==== ??"dkk401!4;;"?a3q6"?@DO}}(!$$t6 !?@@== DMOO$--/344
 	""$ tww		2>DMMB}}- #@s   Ec           	      ~    dj                  | j                         D cg c]  }dt        |      z   c}      S c c}w )zCompute the *printable* MAC tag.

        This method is like `digest`.

        :Return: the MAC, as a hexadecimal string.
         z%02x)r]   r1   r   r~   s     r   	hexdigestzCcmMode.hexdigest  s0     ww$++-@Qa(@AA@s   :c                 H   d| j                   vrt        d      dg| _         | j                          t        d      }t	        j
                  d|| j                        }t	        j
                  d||      }|j                         |j                         k7  rt        d      y)a(  Validate the *binary* MAC tag.

        The caller invokes this function at the very end.

        This method checks if the decrypted message is indeed valid
        (that is, if the key is correct) and it has not been
        tampered with while in transit.

        :Parameters:
          received_mac_tag : bytes/bytearray/memoryview
            This is the *binary* MAC, as received from the sender.
        :Raises ValueError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        r2   z3verify() cannot be called when encrypting a messager!      )digest_bitsrQ   datazMAC check failedN)	rE   ri   r|   r   r   r?   r<   r1   r=   )rO   received_mac_tagsecretmac1mac2s        r   r2   zCcmMode.verify  s    " 4::% 9 : :Z
!"%{{sT]]K{{s=MN;;=DKKM)/00 *r   c                 8    | j                  t        |             y)aW  Validate the *printable* MAC tag.

        This method is like `verify`.

        :Parameters:
          hex_mac_tag : string
            This is the *printable* MAC, as received from the sender.
        :Raises ValueError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        N)r2   r   )rO   hex_mac_tags     r   	hexverifyzCcmMode.hexverify-  s     	Ik*+r   c                 H    | j                  ||      | j                         fS )a\  Perform encrypt() and digest() in one step.

        :Parameters:
          plaintext : bytes/bytearray/memoryview
            The piece of data to encrypt.
        :Keywords:
          output : bytearray/memoryview
            The location where the ciphertext must be written to.
            If ``None``, the ciphertext is returned.
        :Return:
            a tuple with two items:

            - the ciphertext, as ``bytes``
            - the MAC tag, as ``bytes``

            The first item becomes ``None`` when the ``output`` parameter
            specified a location for the result.
        rt   )r/   r1   )rO   rw   ru   s      r   encrypt_and_digestzCcmMode.encrypt_and_digest<  s"    ( ||If|5t{{}DDr   c                 N    | j                  ||      }| j                  |       |S )a  Perform decrypt() and verify() in one step.

        :Parameters:
          ciphertext : bytes/bytearray/memoryview
            The piece of data to decrypt.
          received_mac_tag : bytes/bytearray/memoryview
            This is the *binary* MAC, as received from the sender.
        :Keywords:
          output : bytearray/memoryview
            The location where the plaintext must be written to.
            If ``None``, the plaintext is returned.
        :Return: the plaintext as ``bytes`` or ``None`` when the ``output``
            parameter specified a location for the result.
        :Raises ValueError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        rt   )r0   r2   )rO   rz   r   ru   rw   s        r   decrypt_and_verifyzCcmMode.decrypt_and_verifyR  s)    & LLFL;	$%r   )r   )N)r   r   r   __doc__rW   rN   rg   r.   r^   r/   r0   r1   r|   r   r2   r   r   r   r   r   r   r   r   =   s[    8tFP#(J
B$LJ@K>ZPd"<B1>,E,r   c           	      p   	 |j                  d      x}}|j                  dd      }|t	        d      }|j                  d| j
                        }|j                  dd      }|j                  dd      }t        |      }t        | ||||||      S # t        $ r}t        dt        |      z         d}~ww xY w)	aN  Create a new block cipher, configured in CCM mode.

    :Parameters:
      factory : module
        A symmetric cipher module from `Crypto.Cipher` (like
        `Crypto.Cipher.AES`).

    :Keywords:
      key : bytes/bytearray/memoryview
        The secret key to use in the symmetric cipher.

      nonce : bytes/bytearray/memoryview
        A value that must never be reused for any other encryption.

        Its length must be in the range ``[7..13]``.
        11 or 12 bytes are reasonable values in general. Bear in
        mind that with CCM there is a trade-off between nonce length and
        maximum message size.

        If not specified, a 11 byte long random string is used.

      mac_len : integer
        Length of the MAC, in bytes. It must be even and in
        the range ``[4..16]``. The default is 16.

      msg_len : integer
        Length of the message to (de)cipher.
        If not specified, ``encrypt`` or ``decrypt`` may only be called once.

      assoc_len : integer
        Length of the associated data.
        If not specified, all data is internally buffered.
    rQ   zMissing parameter: Nr3      rR   rS   rT   )popKeyErrorri   strr   r5   dictr   )	rP   kwargsrQ   er3   rR   rS   rT   rU   s	            r   _create_ccm_cipherr   j  s    F8JJu%%c JJw%E} $jjG$6$67GjjD)G

;-ILM7Cm- -  8-A6778s   B 	B5B00B5)r   __all__rJ   binasciir   Crypto.Util.py3compatr   r   r   Crypto.Util._raw_apir   Crypto.Util.strxorr	   Crypto.Util.numberr
   Crypto.Hashr   Crypto.Randomr   r   rB   r=   r   objectr   r   r   r   r   <module>r      sg   > +  0 0 4 % ,  *# QQQO		Z 	jf jZ1-r   