
    ,h1S                        d Z dgZddl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mZmZmZmZmZmZ dd
lmZ dZd Zd Z e       Zd Z e       Z G d de      Z d Z! e!dd      Z" G d de      Z#d Z$y)z
Galois/Counter Mode (GCM).
GcmMode    )	unhexlify)bord_copy_bytes)	is_buffer)long_to_bytesbytes_to_long)BLAKE2s)get_random_bytes)load_pycryptodome_raw_libVoidPointercreate_string_bufferget_raw_bufferSmartPointerc_size_tc_uint8_ptr)_cpu_featuresa`  
    int ghash_%imp%(uint8_t y_out[16],
                    const uint8_t block_data[],
                    size_t len,
                    const uint8_t y_in[16],
                    const void *exp_key);
    int ghash_expand_%imp%(const uint8_t h[16],
                           void **ghash_tables);
    int ghash_destroy_%imp%(void *ghash_tables);
c                     ddl m} d} |d|      }	 |D cg c]  }t        | |dz   |z          }}t	        t        ||            } |di |S c c}w # t        $ r	 d gdz  }Y 3w xY w)Nr   )
namedtuple)ghashghash_expandghash_destroy
_GHash_Imp_    )collectionsr   getattrAttributeErrordictzip)libpostfixr   funcs	GHASH_Impx	imp_funcsparamss           Y/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/Crypto/Cipher/_mode_gcm.py_build_implr*   B   s    &8E</I!?DF!gc1s7W#45F	F #eY'(Fv	 G !HqL	!s!   A AA A A&%A&c                  b    t         j                  dd      } t        d|       }t        |d      }|S )N%imp%portablezCrypto.Hash._ghash_portable)_ghash_api_templatereplacer   r*   apir"   results      r)   _get_ghash_portabler3   O   s2    

%
%gz
:C
#$A3
GCj)FM    c                      t        j                         sy	 t        j                  dd      } t	        d|       }t        |d      }|S # t        $ r d}Y |S w xY w)z4Return None if CLMUL implementation is not availableNr,   clmulzCrypto.Hash._ghash_clmul)r   
have_clmulr.   r/   r   r*   OSErrorr0   s      r)   _get_ghash_clmulr9   W   se     ##%!))'7;'(BCHS'* M  Ms   .A AAc                   "    e Zd ZdZd Zd Zd Zy)_GHASHa  GHASH function defined in NIST SP 800-38D, Algorithm 2.

    If X_1, X_2, .. X_m are the blocks of input data, the function
    computes:

       X_1*H^{m} + X_2*H^{m-1} + ... + X_m*H

    in the Galois field GF(2^256) using the reducing polynomial
    (x^128 + x^7 + x^2 + x + 1).
    c                 \   t        |      dk(  sJ || _        t               | _        |j	                  t        |      | j                  j                               }|rt        d|z        t        | j                  j                         |j                        | _        t        d      | _        y )N   z&Error %d while expanding the GHASH key)lenghash_cr   _exp_keyr   r   
address_of
ValueErrorr   getr   r   _last_y)selfsubkeyr?   r2   s       r)   __init__z_GHASH.__init__r   s    6{b  #%%k&&9&*mm&>&>&@BENOO$T]]%6%6%8%,%:%:< ,B/r4   c           	         t        |      dz  dk(  sJ | j                  j                  | j                  t	        |      t        t        |            | j                  | j                  j                               }|rt        d|z        | S )Nr=   r   zError %d while updating GHASH)	r>   r?   r   rD   r   r   r@   rC   rB   )rE   
block_datar2   s      r)   updatez_GHASH.update   sv    :#q((##DLL$/
$;$,S_$=$(LL$(MM$5$5$7	9
 <vEFFr4   c                 ,    t        | j                        S N)r   rD   rE   s    r)   digestz_GHASH.digest   s    dll++r4   N)__name__
__module____qualname____doc__rG   rJ   rN   r   r4   r)   r;   r;   f   s    	0",r4   r;   c                      t        dd|       S )NEnumr   )type)enumss    r)   enumrW      s    E""r4         )PROCESSING_AUTH_DATAPROCESSING_CIPHERTEXTc                   f    e Zd ZdZd Zd Zd Z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  Galois Counter Mode (GCM).

    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*.

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

    See `NIST SP800-38D`_.

    .. _`NIST SP800-38D`: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
    .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html

    :undocumented: __init__
    c                    |j                   | _         | j                   dk7  rt        d      t        |      dk(  rt        d      t        |      st	        d      t        |      dkD  rt        d      t        d d |      | _        	 || _        t        d d |      | _        d | _	        || _
        d|cxk  rdk  st        d	       t        d	      g d
| _        d| _        d| _        d| _         |j                  || j                  j                   fi |j#                  d      }t        | j                        dk(  r| j                  dz   }ndt        | j                        dz  z
  dz  dz   }	| j                  d|	z  z   t%        dt        | j                        z  d      z   }
t'        ||      j)                  |
      j+                         }|d d }t-        |      dz   dz  } |j                  || j                  j.                  f||d|| _        t'        ||      | _         |j                  || j                  j.                  f|dd|| _        d| _        t8        j:                  | _        y )Nr=   zFGCM mode is only available for ciphers that operate on 128 bits blocksr   zNonce cannot be emptyz,Nonce must be bytes, bytearray or memoryview    zNonce exceeds maximum length   z.Parameter 'mac_len' must be in the range 4..16rJ   encryptdecryptrN   verifyFs                      s             rX   l    )initial_valuenoncer4   )
block_sizerB   r>   r   	TypeErrorr   rh   _factory_key_tag_mac_len_next_no_more_assoc_data	_auth_len_msg_lennewMODE_ECBra   r   r;   rJ   rN   r	   MODE_CTR_cipher_signer_tag_cipher_cache	MacStatusrZ   _status)rE   factorykeyrh   mac_lencipher_paramsr?   hash_subkeyj0fillghash_in	nonce_ctriv_ctrs                r)   rG   zGcmMode.__init__   s   !,,??b  @ A A u:?455JKK u:	!;<< !tU3
dC0		W""MNN #MNN*
 $)    "gkk#"&--"8"8$$1$ %,GL$9 	 tzz?b 11B#djj/B./259D

$'%a#djj/&91=>H W-44X>EEGB sG	#a':5"w{{3#'==#9#9417)24 &3	4 k73 '7;;s'+}}'='=857-08 *7	8  55r4   c                     d| j                   vrt        d      g d| _         | j                  |       | xj                  t	        |      z  c_        | j                  dkD  rt        d      | 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 GCM, 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.
        rJ   z<update() can only be called immediately after initializationr`   r^   z4Additional Authenticated Data exceeds maximum length)ro   rj   _updaterq   r>   rB   )rE   
assoc_datas     r)   rJ   zGcmMode.update  sm    . 4::% @ A A*
 	Z #j/) >>I%STTr4   c                     t        | j                        dk  sJ t        | j                        dkD  rt        dt        | j                        z
  t        |            }| xj                  t        d ||      z  c_        ||d  }t        | j                        dk  ry | j                  j                  | j                         d| _        t        |      dz  dz  }t        |d |      | _        |dkD  r| j                  j                  |d |        y y )Nr=   r   r4   )r>   ry   minr   rw   rJ   )rE   datafiller
update_lens       r)   r   zGcmMode._update-  s    4;;"$%t{{ac$++..D	:FKK;tVT::K=D4;;"$ LL,DKY"_r)
!*dD9>LL[j 12 r4   c                     t        | j                        dk  sJ t        | j                        }|dkD  r| j                  dd|z
  z         y y )Nr=   r   rf   )r>   ry   r   )rE   	len_caches     r)   _pad_cache_and_updatezGcmMode._pad_cache_and_updateA  sG    4;;"$% $	q=LLBN34 r4   Nc                    d| j                   vrt        d      ddg| _         | j                  j                  ||      }| j                  t
        j                  k(  r%| j                          t
        j                  | _        | j                  ||n|       | xj                  t        |      z  c_
        | j                  dkD  rt        d      |S )a  Encrypt data with the key and the parameters 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.

        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``.
        ra   z@encrypt() can only be called after initialization or an update()rN   outputl    z Plaintext exceeds maximum length)ro   rj   rv   ra   r{   rz   rZ   r   r[   r   rr   r>   rB   )rE   	plaintextr   
ciphertexts       r)   ra   zGcmMode.encryptN  s    B DJJ& = > >*
\\)))F)C
<<9999&&($::DL6>Zv>Y' ==;&?@@r4   c                 b   d| j                   vrt        d      ddg| _         | j                  t        j                  k(  r%| j                          t        j                  | _        | j                  |       | xj                  t        |      z  c_        | j                  j                  ||      S )a  Decrypt data with the key and the parameters 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.

        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``.
        rb   z@decrypt() can only be called after initialization or an update()rc   r   )ro   rj   r{   rz   rZ   r   r[   r   rr   r>   rv   rb   )rE   r   r   s      r)   rb   zGcmMode.decrypt  s    B DJJ& C D D*
<<9999&&($::DLZ Z(||##Jv#>>r4   c                 d    d| j                   vrt        d      dg| _         | j                         S )a  Compute the *binary* MAC tag in an AEAD mode.

        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.
        rN   zAdigest() cannot be called when decrypting or validating a message)ro   rj   _compute_macrM   s    r)   rN   zGcmMode.digest  s:     4::% 7 8 8Z
  ""r4   c                    | j                   r| j                   S | j                          | j                  t        d| j                  z  d             | j                  t        d| j
                  z  d             | j                  j                         }| j                  j                  |      d| j                   | _         | j                   S )z#Compute MAC without any FSM checks.re   N)rm   r   r   r   rq   rr   rw   rN   rx   ra   rn   )rE   s_tags     r)   r   zGcmMode._compute_mac  s     9999 	""$]1t~~#5q9:]1t}}#4a89##% $$,,U3NT]]C	yyr4   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)joinrN   r   )rE   r&   s     r)   	hexdigestzGcmMode.hexdigest  s0     ww$++-@Qa(@AA@s   :c                 0   d| j                   vrt        d      dg| _         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.
        rc   z3verify() cannot be called when encrypting a messager=      )digest_bitsr}   r   zMAC check failedN)ro   rj   r   r
   rs   r   rN   rB   )rE   received_mac_tagsecretmac1mac2s        r)   rc   zGcmMode.verify  s    " 4::% 9 : :Z
!"%{{s $ 1 1 35{{s 02 ;;=DKKM)/00 *r4   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)rc   r   )rE   hex_mac_tags     r)   	hexverifyzGcmMode.hexverify  s     	Ik*+r4   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.
        r   )ra   rN   )rE   r   r   s      r)   encrypt_and_digestzGcmMode.encrypt_and_digest  s"    ( ||If|5t{{}DDr4   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 : byte string
            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   )rb   rc   )rE   r   r   r   r   s        r)   decrypt_and_verifyzGcmMode.decrypt_and_verify#  s)    & LLFL;	$%r4   rL   )rO   rP   rQ   rR   rG   rJ   r   r   ra   rb   rN   r   r   rc   r   r   r   r   r4   r)   r   r      sP    0P6d%N3(53j-?^#$"B1@,E,r4   c                 F   	 |j                  d      }|j                  dd      }|t	        d      }|j                  dd      }|j                  dd      }|rt
        rt
        }nt        }t        | |||||      S # t        $ r}t        dt        |      z         d}~ww xY w)	a!  Create a new block cipher, configured in Galois Counter Mode (GCM).

    :Parameters:
      factory : module
        A block cipher module, taken from `Crypto.Cipher`.
        The cipher must have block length of 16 bytes.
        GCM has been only defined for `Crypto.Cipher.AES`.

    :Keywords:
      key : bytes/bytearray/memoryview
        The secret key to use in the symmetric cipher.
        It must be 16 (e.g. *AES-128*), 24 (e.g. *AES-192*)
        or 32 (e.g. *AES-256*) bytes long.

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

        There are no restrictions on its length,
        but it is recommended to use at least 16 bytes.

        The nonce shall never repeat for two
        different messages encrypted with the same key,
        but it does not need to be random.

        If not provided, a 16 byte nonce will be randomly created.

      mac_len : integer
        Length of the MAC, in bytes.
        It must be no larger than 16 bytes (which is the default).
    r}   zMissing parameter:Nrh   r=   r~   	use_clmulT)popKeyErrorrj   strr   _ghash_clmul_ghash_portabler   )r|   kwargsr}   erh   r~   r   r?   s           r)   _create_gcm_cipherr   ;  s    @7jj JJw%E} $jjB'G 

;-I\!7CAA  7,s1v5667s   A; ;	B BB N)%rR   __all__binasciir   Crypto.Util.py3compatr   r   Crypto.Util._raw_apir   Crypto.Util.numberr   r	   Crypto.Hashr
   Crypto.Randomr   r   r   r   r   r   r   r   Crypto.Utilr   r.   r*   r3   r   r9   r   objectr;   rW   rz   r   r   r   r4   r)   <module>r      s   > +  3 * ;  *G G G &	 

 &'  !+,V +,\# aqA	]f ]@1Br4   