
    ,h6                         d Z dgZddlmZmZ ddlmZmZ ddlm	Z	 ddl
mZmZ ddlmZ ddlmZ dd	lmZ  G d
 de      Zd Zy)z-
Synthetic Initialization Vector (SIV) mode.
SivMode    )hexlify	unhexlify)bord_copy_bytes)	is_buffer)long_to_bytesbytes_to_long)_S2V)BLAKE2s)get_random_bytesc                   V    e Z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y)r   a  Synthetic Initialization Vector (SIV).

    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.

    Unlike other AEAD modes such as CCM, EAX or GCM, accidental reuse of a
    nonce is not catastrophic for the confidentiality of the message. The only
    effect is that an attacker can tell when the same plaintext (and same
    associated data) is protected with the same key.

    The length of the MAC is fixed to the block size of the underlying cipher.
    The key size is twice the length of the key of the underlying cipher.

    This mode is only available for AES ciphers.

    +--------------------+---------------+-------------------+
    |      Cipher        | SIV MAC size  |   SIV key length  |
    |                    |    (bytes)    |     (bytes)       |
    +====================+===============+===================+
    |    AES-128         |      16       |        32         |
    +--------------------+---------------+-------------------+
    |    AES-192         |      16       |        48         |
    +--------------------+---------------+-------------------+
    |    AES-256         |      16       |        64         |
    +--------------------+---------------+-------------------+

    See `RFC5297`_ and the `original paper`__.

    .. _RFC5297: https://tools.ietf.org/html/rfc5297
    .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
    .. __: http://www.cs.ucdavis.edu/~rogaway/papers/keywrap.pdf

    :undocumented: __init__
    c                    |j                   | _         	 || _        || _        t        |      dvrt	        dt        |      z        |Bt        |      st        d      t        |      dk(  rt	        d      t        d d |      | _        	 t        |      dz  }d | _	        t        |d | || j                        | _        ||d  | _         |j                  |d | |j                  fi | g d| _        y )	N)    0   @   zIncorrect key length (%d bytes)z?When provided, the nonce must be bytes, bytearray or memoryviewr   z*When provided, the nonce must be non-empty   )	ciphermodcipher_paramsupdateencryptdecryptdigestverify)
block_size_factory_cipher_paramslen
ValueErrorr   	TypeErrorr   nonce_mac_tagr   _kdf_subkey_ciphernewMODE_ECB_next)selffactorykeyr"   kwargssubkey_sizes         Y/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/Crypto/Cipher/_mode_siv.py__init__zSivMode.__init__[   s    !,,@$s8<'>SIJJU# abb5zQ !MNN$T47DJ #h!m\k*#*'+':':<	 "+,/ 	C%w'7'7B6B*
    c                     t        |      }|dz  } | j                  j                  | j                  | j                  j                  f|dd| j
                  S )z*Create a new CTR cipher from V in SIV model	    r0   )initial_valuer"   )r
   r   r&   r%   MODE_CTRr   )r)   vv_intqs       r.   _create_ctr_cipherzSivMode._create_ctr_cipher   se     a 66 t}}  ''MM**+ #$	+
 ))+ 	+r0   c                 |    d| j                   vrt        d      g d| _         | j                  j                  |      S )a  Protect one associated data component

        For SIV, the associated data is a sequence (*vector*) of non-empty
        byte strings (*components*).

        This method consumes the next component. It must be called
        once for each of the components that constitue the associated data.

        Note that the components have clear boundaries, so that:

            >>> cipher.update(b"builtin")
            >>> cipher.update(b"securely")

        is not equivalent to:

            >>> cipher.update(b"built")
            >>> cipher.update(b"insecurely")

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

        :Parameters:
          component : bytes/bytearray/memoryview
            The next associated data component.
        r   z<update() can only be called immediately after initializationr   )r(   r!   r$   r   )r)   	components     r.   r   zSivMode.update   sE    4 4::% D E E*
 yy	**r0   c                     t        d      )z
        For SIV, encryption and MAC authentication must take place at the same
        point. This method shall not be used.

        Use `encrypt_and_digest` instead.
        zEencrypt() not allowed for SIV mode. Use encrypt_and_digest() instead.r!   )r)   	plaintexts     r.   r   zSivMode.encrypt         = > 	>r0   c                     t        d      )z
        For SIV, decryption and verification must take place at the same
        point. This method shall not be used.

        Use `decrypt_and_verify` instead.
        zEdecrypt() not allowed for SIV mode. Use decrypt_and_verify() instead.r;   )r)   
ciphertexts     r.   r   zSivMode.decrypt   r=   r0   c                     d| j                   vrt        d      dg| _         | j                  | j                  j	                         | _        | 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.
        r   zAdigest() cannot be called when decrypting or validating a message)r(   r!   r#   r$   derive)r)   s    r.   r   zSivMode.digest   sS     4::% 7 8 8Z
==  II,,.DM}}r0   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)joinr   r   )r)   xs     r.   	hexdigestzSivMode.hexdigest   s0     ww$++-@Qa(@AA@s   :c                 ~   d| j                   vrt        d      dg| _         | j                  | j                  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.
        r   z3verify() cannot be called when encrypting a messageN      )digest_bitsr+   datazMAC check failed)
r(   r!   r#   r$   rA   r   r   r&   r   r    )r)   received_mac_tagsecretmac1mac2s        r.   r   zSivMode.verify   s    " 4::% 9 : :Z
==  II,,.DM!"%{{sT]]K{{s=MN;;=DKKM)/00 *r0   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)r   r   )r)   hex_mac_tags     r.   	hexverifyzSivMode.hexverify  s     	Ik*+r0   Nc                    d| j                   vrt        d      dg| _         t        | d      r%| j                  j	                  | j
                         | j                  j	                  |       | j                  j                         | _        | j                  | j                        }|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.
        r   z@encrypt() can only be called after initialization or an update()r   r"   output)
r(   r!   hasattrr$   r   r"   rA   r#   r7   r   )r)   r<   rU   ciphers       r.   encrypt_and_digestzSivMode.encrypt_and_digest  s    ( DJJ& = > > Z
 4!IITZZ(		#		((*((7~~i~7FFr0   c                 p   d| j                   vrt        d      dg| _         | j                  |      | _        | j                  j	                  ||      }t        | d      r%| j                  j                  | j                         | j                  j                  ||n|       | j                  |       |S )aP  Perform decryption and verification in one step.

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

        You cannot reuse an object for encrypting
        or decrypting other data with the same key.

        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.
          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.
        r   z@decrypt() can only be called after initialization or an update()r   rT   r"   )
r(   r!   r7   _cipherr   rV   r$   r   r"   r   )r)   r?   mac_tagrU   r<   s        r.   decrypt_and_verifyzSivMode.decrypt_and_verify6  s    : DJJ& C D DZ
 ..w7LL((F(C	4!IITZZ(		fn&AGr0   )N)__name__
__module____qualname____doc__r/   r7   r   r   r   r   rF   r   rR   rX   r\    r0   r.   r   r   1   sE    'R$*L
+!+F	>	>&B1B,"GH,r0   c                     	 |j                  d      }|j                  dd      }t	        | |||      S # t        $ r}t        dt        |      z         d}~ww xY w)a-  Create a new block cipher, configured in
    Synthetic Initializaton Vector (SIV) mode.

    :Parameters:

      factory : object
        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.
        It must be 32, 48 or 64 bytes long.
        If AES is the chosen cipher, the variants *AES-128*,
        *AES-192* and or *AES-256* will be used internally.

      nonce : bytes/bytearray/memoryview
        For deterministic encryption, it is not present.

        Otherwise, it is a value that must never be reused
        for encrypting message under this key.

        There are no restrictions on its length,
        but it is recommended to use at least 16 bytes.
    r+   zMissing parameter: Nr"   )popKeyErrorr!   strr   )r*   r,   r+   er"   s        r.   _create_siv_cipherrg   e  s_    88jj JJw%E7C//  8-A6778s   3 	AAAN)r`   __all__binasciir   r   Crypto.Util.py3compatr   r   Crypto.Util._raw_apir   Crypto.Util.numberr	   r
   Crypto.Protocol.KDFr   Crypto.Hashr   Crypto.Randomr   objectr   rg   ra   r0   r.   <module>rq      s<   > + ' 3 * ; $  *qf qh	#0r0   