ffMdZddlZddlmZddlmZmZmZddlm Z m Z ddl m Z ddl mZddlmZdd lmZmZmZmZmZmZmZmZed d ZGd d eZdZdS)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_bytesbchr) long_to_bytes bytes_to_long)strxor)BLAKE2s)get_random_bytes)load_pycryptodome_raw_lib VoidPointercreate_string_bufferget_raw_buffer SmartPointerc_size_t c_uint8_ptr is_bufferzCrypto.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); cjeZdZdZdZdZdZdZdZddZ dd Z d Z d Z d Z d ZdZdZdZdS)OcbModez=Offset Codebook (OCB) mode. :undocumented: __init__ c ^|jdkrtdd|_ tdd||_ t |t ddvrtdt |std||_d|cxkrdksntdd|_ d|_ d|_ gd |_ t|}|d }|jdzd z}t |jd kr4t|dzd dt |z zzdz|jz}nt|dzdz|jz}t!|d dz}t!|d dz} |j||jfi|} | t)jd|dd | } | t-| dd| ddz} t/t1| d|z z ddd} ||}|rtdt5|zt7|_t:|| tAt | |j!}|rtd|ztE|jt:j#|_|$dS)NzFOCB mode is only available for ciphers that operate on 128 bits blocksz#Nonce must be at most 15 bytes longz,Nonce must be bytes, bytearray or memoryviewz+MAC tag must be between 8 and 16 bytes long)updateencryptdecryptdigestverifykey?15sB @zUnknown keywords: z)Error %d while instantiating the OCB mode)% block_size ValueErrorrnoncelenranger TypeError_mac_len_mac_tag_cache_A_cache_P_nextdictpoprrnewMODE_ECBrstructpackr rr_create_base_cipherstrr _state _raw_ocb_libOCB_start_operationgetr address_ofrOCB_stop_operationrelease)selffactoryr.mac_len cipher_paramsparams_without_keyr taglen_mod128 bottom_bitstop_bits ktop_cipherktopstretchoffset_0 raw_cipherresults y/builddir/build/BUILD/imunify360-venv-2.3.5/opt/imunify360/venv/lib64/python3.11/site-packages/Crypto/Cipher/_mode_ocb.py__init__zOcbMode.__init__ssz   # #@AA A@ tU33 * u::U1b\\ ) )BCC C LJKK K G!!!!r!!!!JKK K   *** "-00 $$U++*c1 tz??R  !+,,rCJJ/0JEE -1,455JE59oo, b ??T)!gk#")"288$688 ""6;v/4SbSz/7$9$9::RaR$qs)444 w!7!7"${"2"457999:=00??  G03}3E3EEFF F!mm 11*..2B2B2:2:3x==2I2I26+2H2H2J2JLL  'H%&'' ' #4;??#4#4#/#BDD rct|jt |t |}|rt d|zdS)Nz(Error %d while computing MAC in OCB mode)r@ OCB_updater?rBrrr-)rF assoc_dataassoc_data_lenrSs rT_updatezOcbMode._updatesh(():):)4Z)@)@)1.)A)ACC  RG&PQQ Q R Rrc,d|jvrtdgd|_t|jdkrt dt|jz t|}|xjt d||z c_||d}t|jdkr|Sd|jc|_}||t|dzdz}t |d||_||||S)aProcess 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. rz*>*3*4*466  %f_F$ItW==  rNcd|jvrtd| dg|_ndg|_||tjdS)aEncrypt 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*. rz@encrypt() can only be called after initialization or an update()Nr)r6r1rjr@ OCB_encryptrF plaintexts rTrzOcbMode.encrypt3s_& DJ & &=>> >  "DJJ#DJ <+CYOOOrcd|jvrtd| dg|_ndg|_||tjdS)aDecrypt 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*. rz@decrypt() can only be called after initialization or an update()Nr)r6r1rjr@ OCB_decrypt)rF ciphertexts rTrzOcbMode.decryptPsg& DJ & &=>> >  "DJJ#DJ , 8 )++ +rc |jdS|jr4||jt|jd|_t d}t |j|tt|}|rtd|zt|d|j |_dS)Nrrz+Error %d while computing digest in OCB mode) r3r4rZr/rr@ OCB_digestr?rBrr-rr2)rFmac_tagrSs rT_compute_mac_tagzOcbMode._compute_mac_tagos = $ F = LLDM(:(: ; ; ;DM&r**(():):)0)1#g,,)?)?++  'J%&'' '&w//? rcd|jvrtdt|jdksJdg|_|j||jS)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. rz-digest() cannot be called now for this cipherr)r6r1r/r5r3rurFs rTrzOcbMode.digestsf 4: % %KLL L4=!!Q&&&&Z =  ! ! # # #}rcddd|DS)zCompute the *printable* MAC tag. This method is like `digest`. :Return: the MAC, as a hexadecimal string. c2g|]}dt|zS)z%02x)r).0xs rT z%OcbMode.hexdigest..s#@@@Qa(@@@r)joinrrws rT hexdigestzOcbMode.hexdigests-ww@@$++--@@@AAArcd|jvrtdt|jdksJdg|_|j|t d}tjd||j}tjd||}| | krtddS) aValidate 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. rz-verify() cannot be called now for this cipherrNr) digest_bitsr datazMAC check failed) r6r1r/r5r3rur r r9rr-)rFreceived_mac_tagsecretmac1mac2s rTrzOcbMode.verifys 4: % %KLL L4=!!Q&&&&Z =  ! ! # # #!"%%{sT]KKK{s=MNNN ;;==DKKMM ) )/00 0 * )rcJ|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)rr)rF hex_mac_tags rT hexverifyzOcbMode.hexverifys$ Ik**+++++rc~|||z|fS)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 )rrrms rTencrypt_and_digestzOcbMode.encrypt_and_digests0||I&&7FFrc|||z}|||S)aDecrypted 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. )rr)rFrqrrns rTdecrypt_and_verifyzOcbMode.decrypt_and_verifys;LL,,t||~~=  $%%%r)N)__name__ __module__ __qualname____doc__rUrZrrfrjrrrurrrrrrrrTrrms RRRhRRR+++Z ( ( ()))VPPPP:++++>@@@&0BBB111> , , , G G Grrc  |dd}|td}|dd}n1#t$r$}tdt |zd}~wwxYwt ||||S)aCreate 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"rHrzKeyword missing: )r8r KeyErrorr1r>r)rGkwargsr.rHes rT_create_ocb_cipherrs06 7D)) =$R((E**Y++ 666+c!ff45556 7E7F 3 33s=A A. A))A.)rr;binasciirCrypto.Util.py3compatrrrCrypto.Util.numberrrCrypto.Util.strxorr Crypto.Hashr Crypto.Randomr Crypto.Util._raw_apir r rrrrrrr@objectrrrrrTrsf>&&P 9999999999;;;;;;;;%%%%%%******-------------------- )()AD()) .DDDDDfDDDN 4 4 4 4 4r