ff1S,dZdgZddlmZddlmZmZddlmZddl m Z m Z ddl m Z ddlmZdd lmZmZmZmZmZmZmZdd lmZd Zd Zd ZeZdZeZGddeZ dZ!e!ddZ"GddeZ#dZ$dS)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 VoidPointercreate_string_bufferget_raw_buffer SmartPointerc_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); cddlm}d}|d|} fd|D}n#t$r dgdz}YnwxYwtt ||}|di|S)Nr) namedtuple)ghash ghash_expand ghash_destroy _GHash_Impc<g|]}t|dzzS)_)getattr).0xlibpostfixs y/builddir/build/BUILD/imunify360-venv-2.3.5/opt/imunify360/venv/lib64/python3.11/site-packages/Crypto/Cipher/_mode_gcm.py z_build_impl..Hs,FFF!gc1s7W#455FFF) collectionsrAttributeErrordictzip)rr rfuncs GHASH_Imp imp_funcsparamss`` r! _build_implr.Bs&&&&&& 8E <//I!FFFFFuFFF !!!HqL ! #eY'' ( (F 9  v  s (;;c|tdd}td|}t|d}|S)N%imp%portablezCrypto.Hash._ghash_portable)_ghash_api_templatereplacer r.apirresults r!_get_ghash_portabler7Os;  % %gz : :C #$A3 G GC j ) )F Mr#ctjsdS tdd}t d|}t |d}n#t $rd}YnwxYw|S)z4Return None if CLMUL implementation is not availableNr0clmulzCrypto.Hash._ghash_clmul)r have_clmulr2r3r r.OSErrorr4s r!_get_ghash_clmulr<Ws~  # % %t!))'7;;'(BCHHS'**  Ms;A A"!A"c$eZdZdZdZdZdZdS)_GHASHaGHASH 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). ct|dksJ||_t|_|t ||j}|rtd|zt|j |j |_td|_ dS)Nz&Error %d while expanding the GHASH key) lenghash_cr _exp_keyrr address_of ValueErrorrgetrr_last_y)selfsubkeyrBr6s r!__init__z_GHASH.__init__rs6{{b     #  %%k&&9&9&*m&>&>&@&@BB  PENOO O$T]%6%6%8%8%,%:<< ,B// r#c *t|dzdksJ|j|jt |t t||j|j}|rtd|z|S)Nr@rzError %d while updating GHASH) rArBrrGrrrCrFrE)rH block_datar6s r!updatez _GHASH.updates:#q((((##DL$/ $;$;$,S__$=$=$(L$(M$5$5$7$7 99  Gr>fsK  000"   ,,,,,r#r>c $tdd|S)NEnumr%)type)enumss r!enumrZs E " ""r#)PROCESSING_AUTH_DATAPROCESSING_CIPHERTEXTcheZdZdZdZdZdZdZddZddZ d Z d Z d Z d Z d ZddZddZdS)raGalois 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|_|jdkrtdt|dkrtdt|st dt|dkrtdt dd||_ ||_t dd||_d|_ ||_ d|cxkrdksntd gd |_ d |_ d|_ d|_|j||jjfi|d }t|jd kr |jdz}ndt|jdzz dzdz} |jd| zzt%dt|jzdz} t'||| }|dd } t-|dzdz} |j||jjf| | d||_t'|||_|j||jjf|dd||_d|_t8j|_dS)Nr@zFGCM mode is only available for ciphers that operate on 128 bits blocksrzNonce cannot be emptyz,Nonce must be bytes, bytearray or memoryviewzNonce exceeds maximum lengthz.Parameter 'mac_len' must be in the range 4..16rMencryptdecryptrQverifyFs sr[l) initial_valuenoncer#) block_sizerErAr TypeErrorrrk_factory_key_tag_mac_len_next_no_more_assoc_data _auth_len_msg_lennewMODE_ECBrdrr>rMrQr MODE_CTR_cipher_signer _tag_cipher_cache MacStatusr]_status) rHfactorykeyrkmac_len cipher_paramsrB hash_subkeyj0fillghash_in nonce_ctriv_ctrs r!rJzGcmMode.__init__s!, ?b @AA A u::??455 5 LJKK K u:: ! !;<< <!tU33  dC00   W""""""""MNN N*** $)  "gk#"&-"8$$$1$$%,GL$9$9  tz??b 11BB#dj//B./259D $'%a#dj//&91==>H W--44X>>EEGGBssG ##a':5"w{3#'=#9417)244&3 44 k733 '7;s'+}'=857-088*7 88  5 r#cd|jvrtdgd|_|||xjt |z c_|jdkrt d|S)axProtect 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. rMzI % %STT T r#cJt|jdksJt|jdkrtdt|jz t|}|xjtd||z c_||d}t|jdkrdS|j|jd|_t|dzdz}t|d||_|dkr$|j|d|dSdS)Nr@rr#)rAr|minrrzrM)rHdatafiller update_lens r!rzGcmMode._update-s4;"$$$$ t{  a  c$+...D ::F KK;tVT:: :KK=D4;"$$ L   , , ,DKYY"_r) !*dD99 >> L  [j[ 1 2 2 2 2 2 >r#ct|jdksJt|j}|dkr|dd|z zdSdS)Nr@rri)rAr|r)rH len_caches r!_pad_cache_and_updatezGcmMode._pad_cache_and_updateAs_4;"$$$$ $$ q== LLBN3 4 4 4 4 4 =r#Ncd|jvrtdddg|_|j||}|jt jkr%|t j|_| ||n||xj t|z c_ |j dkrtd|S)aEncrypt 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``. rdz@encrypt() can only be called after initialization or an update()rQoutputNlz Plaintext exceeds maximum length) rrrmryrdr~r}r]rr^rrurArE)rH plaintextr ciphertexts r!rdzGcmMode.encryptNsB DJ & &=>> >* \)))F)CC <99 9 9  & & ( ( ($:DL 6>ZZv>>> Y'  =; & &?@@ @r#cTd|jvrtdddg|_|jtjkr%|tj|_|||xjt|z c_|j ||S)aDecrypt 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``. rez@decrypt() can only be called after initialization or an update()rfr) rrrmr~r}r]rr^rrurAryre)rHrrs r!rezGcmMode.decryptsB DJ & &CDD D* <99 9 9  & & ( ( ($:DL Z    Z( |##Jv#>>>r#cjd|jvrtddg|_|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. rQzAdigest() cannot be called when decrypting or validating a message)rrrm _compute_macrPs r!rQzGcmMode.digestsC 4: % %788 8Z   """r#c|jr|jS||td|jzd|td|jzd|j}|j |d|j |_|jS)z#Compute MAC without any FSM checks.rhN) rprrrrtrurzrQr{rdrq)rHs_tags r!rzGcmMode._compute_macs 9 9  ""$$$ ]1t~#5q99::: ]1t}#4a88999 ##%%$,,U33NT]NC yr#cddd|DS)zCompute the *printable* MAC tag. This method is like `digest`. :Return: the MAC, as a hexadecimal string. c2g|]}dt|zS)z%02x)r)rrs r!r"z%GcmMode.hexdigest..s#@@@Qa(@@@r#)joinrQrPs r! hexdigestzGcmMode.hexdigests-ww@@$++--@@@AAAr#cVd|jvrtddg|_td}tjd||}tjd||}||krtddS)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. rfz3verify() cannot be called when encrypting a messager@) digest_bitsrrzMAC check failedN)rrrmr r rvrrQrE)rHreceived_mac_tagsecretmac1mac2s r!rfzGcmMode.verifys" 4: % %9:: :Z !"%%{s $ 1 1 3 3555{s 0222 ;;==DKKMM ) )/00 0 * )r#cJ|t|dS)aWValidate 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)rfr)rH hex_mac_tags r! hexverifyzGcmMode.hexverifys$ Ik**+++++r#cX||||fS)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)rdrQ)rHrrs r!encrypt_and_digestzGcmMode.encrypt_and_digest s'(||If|55t{{}}DDr#c^|||}|||S)aPerform 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)rerf)rHrrrrs r!decrypt_and_verifyzGcmMode.decrypt_and_verify#s2&LLFL;;  $%%%r#rO)rRrSrTrUrJrMrrrdrerQrrrfrrrr%r#r!rrs0P6P6P6d%%%N333( 5 5 53333j-?-?-?-?^###$"BBB111@ , , ,EEEE,r#c  |d}n1#t$r$}tdt|zd}~wwxYw|dd}|t d}|dd}|dd}|rt rt }nt }t||||||S) 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). rzMissing parameter:Nrkr@r use_clmulT)popKeyErrorrmstrr _ghash_clmul_ghash_portabler)rkwargsrerkrrrBs r!_create_gcm_cipherr;s@7jj 777,s1vv56667 JJw % %E } $$jjB''G ;--I"\"! 7C A AAs AAAN)%rU__all__binasciirCrypto.Util.py3compatrrCrypto.Util._raw_apirCrypto.Util.numberrr Crypto.Hashr Crypto.Randomr r r rrrrr Crypto.Utilrr2r.r7rr<robjectr>rZr}rrr%r#r!rs> +33333333******;;;;;;;;******GGGGGGGGGGGGGGGGGG&%%%%%     &%''    !! +,+,+,+,+,V+,+,+,\### Daq A A A ]]]]]f]]]@ 1B1B1B1B1Br#