
    ,hM                         d Z ddlZddlmZ ddlmZmZmZ ddlm	Z	m
Z
 ddl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mZ  ed
d      Z G d de      Zd Zy)ah  
Offset Codebook (OCB) mode.

OCB is Authenticated Encryption with Associated Data (AEAD) cipher mode
designed by Prof. Phillip Rogaway and specified in `RFC7253`_.

The algorithm provides both authenticity and privacy, it is very efficient,
it uses only one key and it can be used in online mode (so that encryption
or decryption can start before the end of the message is available).

This module implements the third and last variant of OCB (OCB3) and it only
works in combination with a 128-bit block symmetric cipher, like AES.

OCB is patented in US but `free licenses`_ exist for software implementations
meant for non-military purposes.

Example:
    >>> from Crypto.Cipher import AES
    >>> from Crypto.Random import get_random_bytes
    >>>
    >>> key = get_random_bytes(32)
    >>> cipher = AES.new(key, AES.MODE_OCB)
    >>> plaintext = b"Attack at dawn"
    >>> ciphertext, mac = cipher.encrypt_and_digest(plaintext)
    >>> # Deliver cipher.nonce, ciphertext and mac
    ...
    >>> cipher = AES.new(key, AES.MODE_OCB, nonce=nonce)
    >>> try:
    >>>     plaintext = cipher.decrypt_and_verify(ciphertext, mac)
    >>> except ValueError:
    >>>     print "Invalid message"
    >>> else:
    >>>     print plaintext

:undocumented: __package__

.. _RFC7253: http://www.rfc-editor.org/info/rfc7253
.. _free licenses: http://web.cs.ucdavis.edu/~rogaway/ocb/license.htm
    N)	unhexlify)bord_copy_bytesbchr)long_to_bytesbytes_to_long)strxor)BLAKE2s)get_random_bytes)load_pycryptodome_raw_libVoidPointercreate_string_bufferget_raw_bufferSmartPointerc_size_tc_uint8_ptr	is_bufferzCrypto.Cipher._raw_ocba  
                                    int OCB_start_operation(void *cipher,
                                        const uint8_t *offset_0,
                                        size_t offset_0_len,
                                        void **pState);
                                    int OCB_encrypt(void *state,
                                        const uint8_t *in,
                                        uint8_t *out,
                                        size_t data_len);
                                    int OCB_decrypt(void *state,
                                        const uint8_t *in,
                                        uint8_t *out,
                                        size_t data_len);
                                    int OCB_update(void *state,
                                        const uint8_t *in,
                                        size_t data_len);
                                    int OCB_digest(void *state,
                                        uint8_t *tag,
                                        size_t tag_len);
                                    int OCB_stop_operation(void *state);
                                    c                   h    e Zd 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 Zd Zy)OcbModez=Offset Codebook (OCB) mode.

    :undocumented: __init__
    c           	         |j                   dk7  rt        d      d| _         	 t        d d |      | _        	 t	        |      t        dd      vrt        d      t        |      st        d      || _        d|cxk  rdk  st        d       t        d      d | _	        d| _
        d| _        g d	| _        t        |      }|j                  d
      }| j                  dz  dz  }t	        | j                        dk  r1t        |dz        ddt	        |      z
  z  z   dz   | j                  z   }nt        |dz  dz        | j                  z   }t!        |d         dz  }t!        |d         dz  }	 |j"                  ||j$                  fi |}
|
j'                  t)        j*                  d|d d |	            }|t-        |d d |dd       z   }t/        t1        |      d|z
  z	  d      dd  }|j3                  |      }|rt        dt5        |      z         t7               | _        t:        j=                  |j?                         |tA        t	        |            | j8                  jC                               }|rt        d|z        tE        | j8                  j?                         t:        jF                        | _        |jI                          y )N   zFOCB mode is only available for ciphers that operate on 128 bits blocks   z#Nonce must be at most 15 bytes longz,Nonce must be bytes, bytearray or memoryview   z+MAC tag must be between 8 and 16 bytes long    )updateencryptdecryptdigestverifykey                ?      15sB	   @      zUnknown keywords: z)Error %d while instantiating the OCB mode)%
block_size
ValueErrorr   noncelenranger   	TypeError_mac_len_mac_tag_cache_A_cache_P_nextdictpopr   r   newMODE_ECBr   structpackr	   r   r   _create_base_cipherstrr   _state_raw_ocb_libOCB_start_operationgetr   
address_ofr   OCB_stop_operationrelease)selffactoryr.   mac_lencipher_paramsparams_without_keyr    taglen_mod128bottom_bitstop_bitsktop_cipherktopstretchoffset_0
raw_cipherresults                   Y/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/Crypto/Cipher/_mode_ocb.py__init__zOcbMode.__init__s   s   # @ A A @ tU3
*u:U1b\)BCCJKKG!r!JKK "JKK   *
 "-0 $$U+*c1tzz?R!+,rCJ/0 JJE
 -1,45JJE 59o,b	?T)!gkk#")"2"28$68 ""6;;v/4Sbz/7$9 : Ra$q)44 w!7"${"2"45799:= 00?
03}3EEFF!m11*..2B2:2:3x=2I26++2H2H2JL H%& ' '
 #4;;??#4#/#B#BD
 	r   c                     t         j                  | j                  j                         t	        |      t        |            }|rt        d|z        y )Nz(Error %d while computing MAC in OCB mode)r@   
OCB_updater?   rB   r   r   r-   )rF   
assoc_dataassoc_data_lenrS   s       rT   _updatezOcbMode._update   sK    (():)4Z)@)1.)AC G&PQQ r   c                    d| j                   vrt        d      g d| _         t        | j                        dkD  rt	        dt        | j                        z
  t        |            }| xj                  t        d||      z  c_        ||d }t        | j                        dk  r| S d| j                  c| _        }| j                  |       t        |      dz  dz  }t        |d|      | _        | j                  ||       | S )a  Process the associated data.

        If there is any associated data, the caller has to invoke
        this method 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 shall still able to detect modifications.

        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.
        r   z<update() can only be called immediately after initialization)r   r   r   r   r   r   r   Nr   )r6   r1   r/   r4   minr   r   rZ   )rF   rX   fillerseg
update_lens        rT   r   zOcbMode.update   s    * 4::% @ A A*
 t}}!c$--00#j/BFMM[vzBBM#FG,J4==!B& "%dmmDM3KK_*R/
#JjAZ,r   c                     t        |      } || j                  j                         ||t        |            }|rt	        d||fz        t        |      S )Nz Error %d while %sing in OCB mode)r   r?   rB   r   r-   r   )rF   in_datain_data_len
trans_func
trans_descout_datarS   s          rT   _transcrypt_alignedzOcbMode._transcrypt_aligned   s`     (4DKKOO-#$$[13 ? &
34 5 5h''r   c                    |:| j                  | j                  t        | j                        ||      }d| _        |S d}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                  t        | j                        ||      }d| _        t        |      dz  dz  }| j                  t        |      |||      }|r||z   }t	        |d |      | _        |S )Nr   r   r   )rf   r5   r/   r\   r   r   )	rF   ra   rc   rd   re   prefixr]   	trans_lenrS   s	            rT   _transcryptzOcbMode._transcrypt  s9   ?//03DMM0B0:0:<H  DMO t}}!c$--00#g,?FMM[vw??Mfg&G4==!B&  --dmm.1$--.@.8.8:F  DM LB&+	))+g*>*3*4*46 f_F $ItW=r   Nc                     d| j                   vrt        d      |	dg| _         ndg| _         | j                  |t        j                  d      S )a  Encrypt the next piece of plaintext.

        After the entire plaintext has been passed (but before `digest`),
        you **must** call this method one last time with no arguments to collect
        the final piece of ciphertext.

        If possible, use the method `encrypt_and_digest` instead.

        :Parameters:
          plaintext : bytes/bytearray/memoryview
            The next piece of data to encrypt or ``None`` to signify
            that encryption has finished and that any remaining ciphertext
            has to be produced.
        :Return:
            the ciphertext, as a byte string.
            Its length may not match the length of the *plaintext*.
        r   z@encrypt() can only be called after initialization or an update()r   )r6   r1   rj   r@   OCB_encryptrF   	plaintexts     rT   r   zOcbMode.encrypt3  sW    & DJJ& = > > "DJ#DJ	<+C+CYOOr   c                     d| j                   vrt        d      |	dg| _         ndg| _         | j                  |t        j                  d      S )a  Decrypt the next piece of ciphertext.

        After the entire ciphertext has been passed (but before `verify`),
        you **must** call this method one last time with no arguments to collect
        the remaining piece of plaintext.

        If possible, use the method `decrypt_and_verify` instead.

        :Parameters:
          ciphertext : bytes/bytearray/memoryview
            The next piece of data to decrypt or ``None`` to signify
            that decryption has finished and that any remaining plaintext
            has to be produced.
        :Return:
            the plaintext, as a byte string.
            Its length may not match the length of the *ciphertext*.
        r   z@decrypt() can only be called after initialization or an update()r   )r6   r1   rj   r@   OCB_decrypt)rF   
ciphertexts     rT   r   zOcbMode.decryptP  s]    & DJJ& = > > "DJ#DJ
 , 8 8 )+ 	+r   c           	         | j                   y | j                  r6| j                  | j                  t        | j                               d| _        t	        d      }t
        j                  | j                  j                         |t        t        |                  }|rt        d|z        t        |      d | j                   | _         y )Nr   r   z+Error %d while computing digest in OCB mode)r3   r4   rZ   r/   r   r@   
OCB_digestr?   rB   r   r-   r   r2   )rF   mac_tagrS   s      rT   _compute_mac_tagzOcbMode._compute_mac_tago  s    ==$==LLDMM(:;DM&r*(():)0)1#g,)?+ J%& ' '&w/?r   c                     d| j                   vrt        d      t        | j                        dk(  sJ dg| _         | j                  | j                          | j                  S )a#  Compute the *binary* MAC tag.

        Call this method after the final `encrypt` (the one with no arguments)
        to obtain the MAC tag.

        The MAC tag is needed by the receiver to determine authenticity
        of the message.

        :Return: the MAC, as a byte string.
        r   z-digest() cannot be called now for this cipherr   )r6   r1   r/   r5   r3   ru   )rF   s    rT   r   zOcbMode.digest  sY     4::%KLL4==!Q&'Z
== !!#}}r   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   )rF   xs     rT   	hexdigestzOcbMode.hexdigest  s0     ww$++-@Qa(@AA@s   :c                    d| j                   vrt        d      t        | j                        dk(  sJ dg| _         | j                  | j                          t        d      }t        j                  d|| j                        }t        j                  d||      }|j                         |j                         k7  rt        d      y)	a  Validate the *binary* MAC tag.

        Call this method after the final `decrypt` (the one with no arguments)
        to check if the message is authentic and valid.

        :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   z-verify() cannot be called now for this cipherr   Nr      )digest_bitsr    datazMAC check failed)r6   r1   r/   r5   r3   ru   r   r
   r9   r   r-   )rF   received_mac_tagsecretmac1mac2s        rT   r   zOcbMode.verify  s     4::%KLL4==!Q&'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)r   r   )rF   hex_mac_tags     rT   	hexverifyzOcbMode.hexverify  s     	Ik*+r   c                 f    | j                  |      | j                         z   | j                         fS )a&  Encrypt the message and create the MAC tag in one step.

        :Parameters:
          plaintext : bytes/bytearray/memoryview
            The entire message to encrypt.
        :Return:
            a tuple with two byte strings:

            - the encrypted data
            - the MAC
        )r   r   rm   s     rT   encrypt_and_digestzOcbMode.encrypt_and_digest  s)     ||I&7FFr   c                 l    | j                  |      | j                         z   }| j                  |       |S )a  Decrypted the message and verify its authenticity in one step.

        :Parameters:
          ciphertext : bytes/bytearray/memoryview
            The entire message to decrypt.
          received_mac_tag : byte string
            This is the *binary* MAC, as received from the sender.

        :Return: the decrypted data (byte string).
        :Raises ValueError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        )r   r   )rF   rq   r   rn   s       rT   decrypt_and_verifyzOcbMode.decrypt_and_verify  s0     LL,t||~=	$%r   )N)__name__
__module____qualname____doc__rU   rZ   r   rf   rj   r   r   ru   r   r{   r   r   r   r    r   rT   r   r   m   sV    
RhR+Z()VP:+>@&0B1>,Gr   r   c                     	 |j                  dd      }|t        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 OCB mode.

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

    :Keywords:
      nonce : bytes/bytearray/memoryview
        A  value that must never be reused for any other encryption.
        Its length can vary from 1 to 15 bytes.
        If not specified, a random 15 bytes long nonce is generated.

      mac_len : integer
        Length of the MAC, in bytes.
        It must be in the range ``[8..16]``.
        The default is 16 (128 bits).

    Any other keyword will be passed to the underlying block cipher.
    See the relevant documentation for details (at least ``key`` will need
    to be present).
    r.   Nr"   rH   r   zKeyword missing: )r8   r   KeyErrorr1   r>   r   )rG   kwargsr.   rH   es        rT   _create_ocb_cipherr     sp    06

7D)=$R(E**Y+ 7E7F33  6+c!f4556s   1A 	A&
A!!A&)r   r;   binasciir   Crypto.Util.py3compatr   r   r   Crypto.Util.numberr   r   Crypto.Util.strxorr	   Crypto.Hashr
   Crypto.Randomr   Crypto.Util._raw_apir   r   r   r   r   r   r   r   r@   objectr   r   r   r   rT   <module>r      s]   >&P   9 9 ; %  *- - -
 ))A D( ).Df DN 4r   