
    ib                         S r S/rSSKrSSKJr  SSKJrJrJr  SSK	J
r
  SSKJr  SSKJr  SS	KJr  SS
KJr  S r\" SSSS9r " S S\5      r " S S\5      rS rg)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                      [        SSU 5      $ )NEnum )type)enumss    R/var/www/html/trading/venv/lib/python3.13/site-packages/Crypto/Cipher/_mode_ccm.pyenumr   3   s    E""          )NOT_STARTEDPROCESSING_AUTH_DATAPROCESSING_PLAINTEXTc                       \ rS rSrSrg)CCMMessageTooLongError9   r   N)__name__
__module____qualname____firstlineno____static_attributes__r   r   r   r   r   9   s    r   r   c                       \ rS rSrSrS rS rS rS rSS jr	SS	 jr
SS
 jrS rS rS rS rS rSS jrSS jrSrg)r   =   aL
  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           	         UR                   U l          [        S S U5      U l         Xl        [        S S U5      U l        X@l        XPl        X`l        Xpl        S U l	        U R                   S:w  a  [        S5      eUS;  a  [        SU-  5      eS[        U5      s=::  a  S::  d  O  [        S5      eS[        U5      -
  nU(       a/  [        [        U5      5      U:  a  [        S	[        U5      -  5      eU R                  R                  " UUR                  4S
S0UD6U l        ["        R$                  U l        S U l        / SQU l        SU l        SU l        / U l        U R                  R                  " UU R                  R2                  4S[4        R6                  " SUS-
  5      U R                  -   0UD6U l        U R8                  R;                  S5      U l        S Xe4;  a  U R?                  5         g g )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   r7   _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_cipherr3   _s_0
_start_mac)	selffactorykeyr7   mac_lenmsg_len	assoc_lencipher_paramsqs	            r   __init__CcmMode.__init__x   s    ",,@ tU3
5dC0	#+??b  @ A A 33 @BIJ K K SZ%2% 9 : : UOs=12Q6()ORUV[R\)\]] MM%%c&-&6&67)57 )67	 %00*
 !"
  }}(()-)?)?:/5{{3A/F/S: ,9: LL((6	 	++OO ,r   c                 v   U R                   [        R                  :X  d   eS U R                  U R                  4;  d   e[        U R                  [        5      (       d   eS[        U R                  5      -
  nU R                  S:  S-  nX R                  S-
  S-  S-  -  nX!S-
  -  n[        R                  " SU5      U R                  -   [        U R                  U5      -   nSnU R                  S:  aE  U R                  S	:  a  SnOU R                  S
:  a  SnSnOSnSnU[        U R                  U5      -  nU R                  R                  SU5        U R                  R                  SU5        SR                  U R                  5      nSU l        [        R                   U l         U R#                  U5        g )Nr.   r   r'   r      r   r8   r   i   l        s   r&   s   r(   )rG   rF   r   r>   r=   
isinstancerL   listrB   r7   r<   rN   rO   r
   insertjoinr   _update)rS   rZ   flagsb_0assoc_len_encodedenc_sizefirst_data_to_macs          r   rR   CcmMode._start_mac   s   9#8#8898DOOT]];;<;$++t,,-, TZZ 1$*==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                    U R                   [        R                  :w  d   e[        U R                  5      U R
                  :  d   e[        U R                  5      nUS:  a"  U R                  SU R
                  U-
  -  5        g g )Nr       )rG   rF   r   rB   rL   r9   rc   )rS   	len_caches     r   _pad_cache_and_updateCcmMode._pad_cache_and_update   sm    9#8#88984;;$//121
 $	q=LLDOOi$?@A r   c                    SU R                   ;  a  [        S5      e/ SQU l         U =R                  [        U5      -  sl        U R                  b%  U R                  U R                  :  a  [        S5      eU R                  U5        U $ )a   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.
r2   z<update() can only be called immediately after initializationr1   zAssociated data is too long)rI   	TypeErrorrJ   rB   r>   rA   rc   )rS   
assoc_datas     r   r2   CcmMode.update   s~    . 4::% @ A A*
 	Z0??&  4??2:;;Z r   c                 b   U R                   [        R                  :X  a9  [        U5      (       a  [	        SSU5      nU R
                  R                  U5        g[        U R
                  5      U R                  :  d   e[        U R
                  5      S:  a  [        U R                  [        U R
                  5      -
  [        U5      5      nU =R
                  [	        SX!5      -  sl        [	        USU5      n[        U R
                  5      U R                  :  a  gU R                  R                  U R
                  5      U l        SU l        [        U5      U R                  -  U R                  -  n[	        USU5      U l        US:  a'  U R                  R                  USU 5      SS U l        gg)zEUpdate the MAC with associated data or plaintext
(without FSM checks)Nr   r   i)rG   rF   r   r   r   rL   appendrB   r9   minrE   r3   rH   )rS   assoc_data_ptfiller
update_lens       r   rc   CcmMode._update  sR    y444"=11 +D$ FKK}-4;;$//121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                 R   SU R                   ;  a  [        S5      eSS/U l         U R                  cs  [        U R                  [
        5      (       d   e[        U R                   Vs/ s H  n[        U5      PM     sn5      U l        U R                  b  U R                  5         O%U R                  U R                  :  a  [        S5      eU R                  c  S[        U R                  5      -
  n[        [        [        U5      5      5      U:  a!  [        S[        U R                  5      -  5      e[        U5      U l        U R                  5         S/U l         U =R                  [        U5      -  sl        U R                  U R                  :  a&  SU R                  U R                  4-  n[        U5      eU R                   ["        R$                  :X  a%  U R'                  5         ["        R(                  U l        U R+                  U5        U R,                  R/                  XS9$ s  snf )	a  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``.
r3   z@encrypt() can only be called after initialization or an update()r5   Associated data is too shortr.   r/   6Message longer than declared for (%u bytes vs %u bytesoutput)rI   rp   r>   r_   rL   r`   sumrB   r=   rR   rJ   rA   r7   r
   r   rK   rG   rF   r   rm   r   rc   rP   r3   )rS   	plaintextr~   xrZ   msgs         r   r3   CcmMode.encrypt7  s   J DJJ& = > >*
 ??"dkk40010!4;;"?;a3q6;"?@DO}}(!$$t6 !?@@ == S_$A=Y01A5,-SVYZ^ZdZdVe-eff	NDMOO"DJs9~-.J&&67C(--y=== &&((==DY||##I#==A #@s   &H$c                    SU R                   ;  a  [        S5      eSS/U l         U R                  cs  [        U R                  [
        5      (       d   e[        U R                   Vs/ s H  n[        U5      PM     sn5      U l        U R                  b  U R                  5         O%U R                  U R                  :  a  [        S5      eU R                  c  S[        U R                  5      -
  n[        [        [        U5      5      5      U:  a!  [        S[        U R                  5      -  5      e[        U5      U l        U R                  5         S/U l         U =R                  [        U5      -  sl        U R                  U R                  :  a&  SU R                  U R                  4-  n[        U5      eU R                   ["        R$                  :X  a%  U R'                  5         ["        R(                  U l        U R*                  R-                  XS9nUc  U R/                  U5        U$ U R/                  U5        U$ s  snf )	a  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``.
r4   z@decrypt() can only be called after initialization or an update()r6   r{   r.   r/   r|   r}   )rI   rp   r>   r_   rL   r`   r   rB   r=   rR   rJ   rA   r7   r
   r   rK   rG   rF   r   rm   r   rP   r3   rc   )rS   
ciphertextr~   r   rZ   r   r   s          r   r4   CcmMode.decrypt  s   J DJJ& C D D*
 ??"dkk40010!4;;"?;a3q6;"?@DO}}(!$$t6 !?@@ == S_$A=Z12Q6,-SVYZ^ZdZdVe-eff
ODMOO"DJs:..J&&67C(--y=== &&((==D LL(((C	>LL#  LL K #@s   &H<c                 h    SU R                   ;  a  [        S5      eS/U l         U R                  5       $ )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.
r5   zAdigest() cannot be called when decrypting or validating a message)rI   rp   _digest)rS   s    r   r5   CcmMode.digest  s7     4::% 7 8 8Z
||~r   c                    U R                   (       a  U R                   $ U R                  cs  [        U R                  [        5      (       d   e[        U R                   Vs/ s H  n[        U5      PM     sn5      U l        U R                  b  U R                  5         O%U R                  U R                  :  a  [        S5      eU R                  c  SU l        U R                  5         U R                  U R                  :w  a  [        S5      eU R                  5         [        U R                  U R                  5      S U R                    U l         U R                   $ s  snf )Nr{   r   zMessage is too short)r@   r>   r_   rL   r`   r   rB   r=   rR   rJ   rA   rK   rm   r	   rH   rQ   r<   rS   r   s     r   r   CcmMode._digest  s   ==== ??"dkk40010!4;;"?;a3q6;"?@DO}}(!$$t6 !?@@== DMOO$--/344
 	""$ tww		2>DMMB}}- #@s   Ec           	          SR                  U R                  5        Vs/ s H  nS[        U5      -  PM     sn5      $ s  snf )zlCompute the *printable* MAC tag.

This method is like `digest`.

:Return: the MAC, as a hexadecimal string.
 z%02x)rb   r5   r   r   s     r   	hexdigestCcmMode.hexdigest	  s4     ww$++-@-Qa(-@AA@s   =c                 B   SU R                   ;  a  [        S5      eS/U l         U R                  5         [        S5      n[        R
                  " SX R                  S9n[        R
                  " SX!S9nUR                  5       UR                  5       :w  a  [        S5      eg)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.
r6   z3verify() cannot be called when encrypting a messager%      )digest_bitsrU   datazMAC check failedN)	rI   rp   r   r   r   rC   r@   r5   rA   )rS   received_mac_tagsecretmac1mac2s        r   r6   CcmMode.verify  s    " 4::% 9 : :Z
!"%{{s]]K{{sN;;=DKKM)/00 *r   c                 8    U R                  [        U5      5        g)a  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)r6   r   )rS   hex_mac_tags     r   	hexverifyCcmMode.hexverify1  s     	Ik*+r   c                 @    U R                  XS9U R                  5       4$ )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}   )r3   r5   )rS   r   r~   s      r   encrypt_and_digestCcmMode.encrypt_and_digest@  s     ( ||I|5t{{}DDr   c                 F    U R                  XS9nU R                  U5        U$ )ak  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.
r}   )r4   r6   )rS   r   r   r~   r   s        r   decrypt_and_verifyCcmMode.decrypt_and_verifyV  s'    & LLL;	$%r   )r>   rL   rP   r?   rJ   rK   r:   r;   rE   r<   rG   r@   r=   rI   rQ   rH   r9   r7   )r   )N)r   r   r   r    __doc__r[   rR   rm   r2   rc   r3   r4   r5   r   r   r6   r   r   r   r!   r   r   r   r   r   =   s[    8tFP#(J
B$LJ@M>^Rh"<B1>,E,r   c           	      j    UR                  S5      nUR                  SS5      nUc  [	        S5      nUR                  SU R
                  5      nUR                  SS5      nUR                  SS5      n[        U5      n[        XXEUXx5      $ ! [         a  n[        S[        U5      -   5      eSnAff = f)	a  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.
rU   zMissing parameter: Nr7      rV   rW   rX   )popKeyErrorrp   strr   r9   dictr   )	rT   kwargsrU   er7   rV   rW   rX   rY   s	            r   _create_ccm_cipherr   n  s    F8JJu%c JJw%E} $jjG$6$67GjjD)G

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