
    ,hwB                        d dl Z d dlmZ d dlmZ d dlmZ ddlmZm	Z	 ddl
mZ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 d dlmZmZ  G d de      Z G d de      Z G d de      Z G d de      ZddefddefddefddefddefdZ de!de!de!d e!d!ef
d"Z"d#e!de!d$e!d%e#d e!d!efd&Z$d'e!d(e!d e!d!efd)Z% G d* d+      Z&ddddd,d-ed.ed/ee!   d0ee   d1ee'e!e!f      d$ee!   d2e&fd3Z(y)4    N)IntEnum)
ModuleType)Optional   )_HKDF_extract_HKDF_expand)key_agreementimport_x25519_public_keyimport_x448_public_key)strxor)ECC)EccKey)SHA256SHA384SHA512)AESChaCha20_Poly1305c                        e Zd ZdZdZdZdZdZy)MODEz
HPKE modesr   r         N)__name__
__module____qualname____doc__BASEPSKAUTHAUTH_PSK     V/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/Crypto/Protocol/HPKE.pyr   r      s    D
CDHr!   r   c                       e Zd ZdZdZdZdZy)AEADz>Authenticated Encryption with Associated Data (AEAD) Functionsr   r   r   N)r   r   r   r   
AES128_GCM
AES256_GCMCHACHA20_POLY1305r    r!   r"   r$   r$      s    HJJr!   r$   c                       e Zd Zy)DeserializeErrorNr   r   r   r    r!   r"   r)   r)          r!   r)   c                       e Zd Zy)MessageLimitReachedErrorNr*   r    r!   r"   r-   r-   "   r+   r!   r-         r      r       !   z
NIST P-256z
NIST P-384z
NIST P-521
Curve25519Curve448saltlabelikmsuite_idhashmodc                 2    d|z   |z   |z   }t        | ||      S )N   HPKE-v1)r   )r6   r7   r8   r9   r:   labeled_ikms         r"   _labeled_extractr>   /   s'    
 x'%/#5K{G44r!   prkinfoLc                 b    t        j                  d|      dz   |z   |z   |z   }t        | |||      S )N>Hr<   )structpackr   )r?   r7   r@   rA   r9   r:   labeled_infos          r"   _labeled_expandrG   8   s?     ;;tQ'*4x? L\1g66r!   dhkem_contextc                 \    |j                   }t        dd| ||      }t        |d||||      }|S )Nr!   s   eae_prks   shared_secret)digest_sizer>   rG   )rH   rI   r9   r:   Nsecreteae_prkshared_secrets          r"   _extract_and_expandrO   C   sL     !!Gs)!'&	(G $G$4$/$+$,$+-M r!   c                       e Zd Zdedee   dee   deeef   dededefdZ	e
	 	 dded
ededee   dee   f
d       Ze
	 ddeded
ededee   f
d       Ze
dedeeef   fd       ZdedededefdZd Zddedee   fdZddedee   fdZy	)HPKE_Cipherreceiver_keyenc
sender_keypsk_pairr@   aead_idmodec                    |dn|| _         	 | j                  ||       |j                  | _        || _        || _        	 t        | j                     \  | _        | _        | _	        | j                  t        j                  k(  rdnd| _        d| _        d| _        | j                  j$                  | _        |j)                          | _        | j*                  r>|t        d      | j-                  || j                  | j                  |      \  }	| _         n6|t        d      | j/                  ||| j                  | j                  |      }	d| _        d	d
| j                   z  z  d	z
  | _         | j4                  |	|g| \  | _        | _        | _        y # t        $ r*}t        dj                  | j                              |d }~ww xY w)Nr!   z!Curve {} is not supported by HPKEr.   r1      z0Parameter 'enc' cannot be an input  when sealingz'Parameter 'enc' required when unsealingr   r      )rS   _verify_psk_inputscurve_curve_aead_id_mode_Curve_Config_kem_id_kdf_id_hashmodKeyError
ValueErrorformatr$   r%   _Nk_Nn_NtrK   _Nhhas_private_encrypt_encap_decap	_sequence_max_sequence_key_schedule_key_base_nonce_export_secret)
selfrR   rS   rT   rU   r@   rV   rW   kerN   s
             r"   __init__zHPKE_Cipher.__init__Z   s    "%##+h/"((
	^ +4;;7DL\] $//92r==,,(4466== !STT&*kk,26,,26--2<'>#M48 { !JKK KK(4(,(,(2	4M AL1Q6 #5$"4"4]59#@6>#@	 	C  	^@GGTU[]]	^s   &F 	G%GGNkem_idr:   eph_keyc                    ||j                         sJ ||j                         sJ | t        j                  | j                        }|j	                         j                  d      }| j	                         j                  d      }||z   }i }|r'||j	                         j                  d      z  }d|i}dt        j                  d|      z   }	||	|fd}
t        d	|| |
d|}||fS )
N)r\   rawrf   static_priv   KEMrC   c                     t        | |||      S NrO   rH   rI   r9   r:   s       r"   kdfzHPKE_Cipher._encap.<locals>.kdf        'r;'JJr!   )eph_priv
static_pubr   r    )	rk   r   generater\   
public_key
export_keyrD   rE   r	   )rR   rx   r:   rT   ry   rS   pkRmrI   extra_paramr9   r   rN   s               r"   rm   zHPKE_Cipher._encap   s    "z'='='??G$7$7$99?ll););<G  "--U-;&&(3353ADj:002==U=KKK(*5KFKKf55 (!	K & 5w1=*-5 )45 c!!r!   c                    |j                         sJ 	 |j                  dk(  rt        |       }n<|j                  dk(  rt        |       }n!t	        j
                  | |j                        }|j                         j                  d      }| |z   }i }	|r'||j                         j                  d      z  }d|i}	dt        j                  d	|      z   }
||
|fd
}t        d|||d|	}|S # t        $ r}t        d      |d }~ww xY w)Nr4   r5   )
curve_namez*'enc' is not a valid encapsulated HPKE keyr{   r|   r   r~   rC   c                     t        | |||      S r   r   r   s       r"   r   zHPKE_Cipher._decap.<locals>.kdf   r   r!   )eph_pubr}   r   r    )rk   r\   r
   r   r   
import_keyre   r)   r   r   rD   rE   r	   )rS   rR   rx   r:   rT   pkEver   rI   r   r9   r   rN   s                r"   rn   zHPKE_Cipher._decap   s-    ''))	Y!!\1.s3##z1,S1nnS\5G5GH &&(3353ADj:002==U=KKK'4KFKKf55 (!	K & 5c2>*-5 )45 -  	Y"#OPVXX	Ys   AC, ,	D5DDc                 F   |\  }}|dk(  |dk(  z  rt        d      |dk(  r;| t        j                  t        j                  fv rt        d| j                         y t        |      dk  rt        d      | t        j                  t        j                  fv rt        d      y )Nr!   zInconsistent PSK inputszPSK is required with mode r1   z!PSK must be at least 32 byte longz$PSK is not compatible with this mode)re   r   r   r   namelenr   r   )rW   rU   psk_idpsks       r"   r[   zHPKE_Cipher._verify_psk_inputs   s    3J6S=)6773J$--00 #=dii[!IJJ 1 3x"} !DEE		499-- !GHH .r!   rN   r   r   c                 0   dt        j                  d| j                  | j                  | j                        z   }t        dd||| j                        }t        dd||| j                        }| j                  j                  dd      |z   |z   }t        |d||| j                        }	t        |	d	|| j                  || j                        }
t        |	d
|| j                  || j                        }t        |	d|| j                  || j                        }|
||fS )Ns   HPKEz>HHHr!   s   psk_id_hashs	   info_hashr   bigs   secrets   keys
   base_nonces   exp)rD   rE   ra   rb   r^   r>   rc   r_   to_bytesrG   rg   rh   rj   )ru   rN   r@   r   r   r9   psk_id_hash	info_hashkey_schedule_contextsecretkey
base_nonceexporter_secrets                r"   rq   zHPKE_Cipher._key_schedule   s)    V[[)-)-)-8 8
 's'5'-'/'+}}	6 %S%1%)%-%)]]	4	  $zz221e<{JYV!-"+"%"*"&--	1 f$2"hh&"mm- %V%2%9%)XX%-%)]]4
 *&*0*>*.((*2*.--9 J//r!   c                 j   t        | j                  | j                  j                  | j                  d            }| j
                  t        j                  t        j                  fv r<t        j                  | j                  t        j                  || j                        }nX| j
                  t        j                  k(  r"t        j                  | j                  |      }nt!        d| j
                  d      | j                  | j"                  k\  r
t%               | xj                  dz  c_        |S )Nr   )noncemac_len)r   r   Unknown AEAD cipher ID #xr   )r   rs   ro   r   rh   r^   r$   r%   r&   r   newrr   MODE_GCMri   r'   r   re   rp   r-   )ru   r   ciphers      r"   _new_cipherzHPKE_Cipher._new_cipher&  s    t'')@)@5)QR==T__doo>>WWTYYE488TF]]d444&**tyyFF6t}}R6HIJJ>>T///*,,!r!   	plaintext	auth_datac                     | j                   st        d      | j                         }|r|j                  |       |j	                  |      \  }}||z   S )a  Encrypt and authenticate a message.

        This method can be invoked multiple times
        to seal an ordered sequence of messages.

        Arguments:
          plaintext: bytes
            The message to seal.
          auth_data: bytes
            Optional. Additional Authenticated data (AAD) that is not encrypted
            but that will be also covered by the authentication tag.

        Returns:
           The ciphertext concatenated with the authentication tag.
        z$This cipher can only be used to seal)rl   re   r   updateencrypt_and_digest)ru   r   r   r   cttags         r"   sealzHPKE_Cipher.seal3  sQ    " }}CDD!!#MM)$++I6CCxr!   
ciphertextc                    | j                   rt        d      t        |      | j                  k  rt        d      | j	                         }|r|j                  |       	 |j                  |d| j                    || j                   d       }|S # t        $ r& | j                  dk(  rt        d      t        d      w xY w)a  Decrypt a message and validate its authenticity.

        This method can be invoked multiple times
        to unseal an ordered sequence of messages.

        Arguments:
          cipertext: bytes
            The message to unseal.
          auth_data: bytes
            Optional. Additional Authenticated data (AAD) that
            was also covered by the authentication tag.

        Returns:
           The original plaintext.

        Raises: ValueError
           If the ciphertext (in combination with the AAD) is not valid.

           But if it is the first time you call ``unseal()`` this
           exception may also mean that any of the parameters or keys
           used to establish the session is wrong or that one is missing.
        z&This cipher can only be used to unsealzCiphertext is too smallNr   zAIncorrect HPKE keys/parameters or invalid message (wrong MAC tag)zInvalid message (wrong MAC tag))rl   re   r   ri   r   r   decrypt_and_verifyro   )ru   r   r   r   pts        r"   unsealzHPKE_Cipher.unsealL  s    0 ==EFFz?TXX%677!!#MM)$	@**:jy+A+5txxij+ACB 		  	@~~" !dee>??	@s   .B /B>)NNr   )r   r   r   r   r   bytestupler$   r   rw   staticmethodintr   rm   rn   r[   rq   r   r   r   r    r!   r"   rQ   rQ   X   s   9@%9@uo9@ &f-9@ !.	9@
 9@ 9@ 9@v  /3+/	 "V  " "" " $F+ " !(	 "  "D 
 /3	%E %#%% #% $F+	% %N I Iue|1D I I40%*40!40 $40 !	40le  2' '8E? 'r!   rQ   )rS   rT   r   r@   rR   rV   rS   rT   r   returnc           	         |t         vrt        d|d      | j                  }|dvrt        d|       |rt        | j	                               t        |j	                               z   }|dk7  rt        d      |j                  |k7  r%t        dj                  |j                  |            |t        j                  nt        j                  }n"|t        j                  nt        j                  }|d}|d	}t        | ||||||      S )
a	  Create an HPKE context which can be used:

    - by the sender to seal (encrypt) a message or
    - by the receiver to unseal (decrypt) it.

    As a minimum, the two parties agree on the receiver's asymmetric key
    (of which the sender will only know the public half).

    Additionally, for authentication purposes, they may also agree on:

    * the sender's asymmetric key (of which the receiver will only know the public half)

    * a shared secret (e.g., a symmetric key derived from a password)

    Args:
      receiver_key:
        The ECC key of the receiver.
        It must be on one of the following curves: ``NIST P-256``,
        ``NIST P-384``, ``NIST P-521``, ``X25519`` or ``X448``.

        If this is a **public** key, the HPKE context can only be used to
        **seal** (**encrypt**).

        If this is a **private** key, the HPKE context can only be used to
        **unseal** (**decrypt**).

      aead_id:
        The HPKE identifier of the symmetric cipher.
        The possible values are:

        * ``HPKE.AEAD.AES128_GCM``
        * ``HPKE.AEAD.AES256_GCM``
        * ``HPKE.AEAD.CHACHA20_POLY1305``

      enc:
        The encapsulated session key (i.e., the KEM shared secret).

        The receiver must always specify this parameter.

        The sender must always omit this parameter.

      sender_key:
        The ECC key of the sender.
        It must be on the same curve as the ``receiver_key``.
        If the ``receiver_key`` is a public key, ``sender_key`` must be a
        private key, and vice versa.

      psk:
        A Pre-Shared Key (PSK) as a 2-tuple of non-empty
        byte strings: the identifier and the actual secret value.
        Sender and receiver must use the same PSK (or none).

        The secret value must be at least 32 bytes long,
        but it  must not be a low-entropy password
        (use a KDF like PBKDF2 or scrypt to derive a secret
        from a password).

      info:
        A non-secret parameter that contributes
        to the generation of all session keys.
        Sender and receive must use the same **info** parameter (or none).

    Returns:
        An object that can be used for
        sealing (if ``receiver_key`` is a public key) or
        unsealing (if ``receiver_key`` is a private key).
        In the latter case,
        correctness of all the keys and parameters will only
        be assessed with the first call to ``unseal()``.

    .. _HPKE: https://datatracker.ietf.org/doc/rfc9180/
    r   r   r3   zUnsupported curve r   zExactly 1 private key requiredz'Sender key uses {} but recipient key {})r!   r!   r!   )r$   re   r\   r   rk   rf   r   r   r   r   r   rQ   )	rR   rV   rS   rT   r   r@   r\   count_private_keysrW   s	            r"   r   r   v  s   ^ d272,?@@E / /-eW566 !9!9!;< !7!7!9:;"=>>u$F#VJ$4$4e<> >KtyyT]]KtyyTXX
{||! r!   ))rD   enumr   typesr   typingr   KDFr   r   DHr	   r
   r   Crypto.Util.strxorr   Crypto.PublicKeyr   Crypto.PublicKey.ECCr   Crypto.Hashr   r   r   Crypto.Cipherr   r   r   r$   re   r)   r-   r`   r   r>   r   rG   rO   rQ   r   r   r    r!   r"   <module>r      s       , O O %   ' . . 07 7 	z 		z 	
 (((((55 5!55  %5 )	57 7 77 7 $	7
 (7E %*"' ",*[ [@	  $'+-1 $o ooe_o V$o eE5L)*	o
 uoo
 *5or!   