o
    n~bM                     @   s  d dl Z d dlZd dlmZ d dlmZmZmZmZm	Z	m
Z
mZ d dlmZmZmZmZ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mZmZ ed	d
Z eddZ!d$ddZ"d%ddZ#G dd de$Z%d&ddZ&d'ddZ'dd Z(dd Z)dd Z*d(d d!Z+d"d# Z,dS ))    N)reduce)tobytesbord_copy_bytes
iter_rangetostrbchrbstr)SHA1SHA256HMACCMACBLAKE2s)strxor)get_random_bytes)sizelong_to_bytesbytes_to_long)load_pycryptodome_raw_libcreate_string_bufferget_raw_bufferc_size_tzCryptodome.Cipher._Salsa20z
                    int Salsa20_8_core(const uint8_t *x, const uint8_t *y,
                                       uint8_t *out);
                    zCryptodome.Protocol._scrypta  
                    typedef int (core_t)(const uint8_t [64], const uint8_t [64], uint8_t [64]);
                    int scryptROMix(const uint8_t *data_in, uint8_t *data_out,
                           size_t data_len, unsigned N, core_t *core);
                      c                 C   s   |st }t| } || | }|j}||krtd| t|dkr*tdt| t|d D ]	}|| }q0| d| S )aY  Derive one key from a password (or passphrase).

    This function performs key derivation according to an old version of
    the PKCS#5 standard (v1.5) or `RFC2898
    <https://www.ietf.org/rfc/rfc2898.txt>`_.

    Args:
     password (string):
        The secret password to generate the key from.
     salt (byte string):
        An 8 byte string to use for better protection from dictionary attacks.
        This value does not need to be kept secret, but it should be randomly
        chosen for each derivation.
     dkLen (integer):
        The length of the desired key. The default is 16 bytes, suitable for
        instance for :mod:`Cryptodome.Cipher.AES`.
     count (integer):
        The number of iterations to carry out. The recommendation is 1000 or
        more.
     hashAlgo (module):
        The hash algorithm to use, as a module or an object from the :mod:`Cryptodome.Hash` package.
        The digest length must be no shorter than ``dkLen``.
        The default algorithm is :mod:`Cryptodome.Hash.SHA1`.

    Return:
        A byte string of length ``dkLen`` that can be used as key.
    z:Selected hash algorithm has a too short digest (%d bytes).   z,Salt is not 8 bytes long (%d bytes instead).   N)	r
   r   newdigest_size	TypeErrorlen
ValueErrorr   digest)passwordsaltdkLencountZhashAlgoZpHashr    i r&   B/usr/local/lib/python3.10/dist-packages/Cryptodome/Protocol/KDF.pyPBKDF17   s   r(      c           
         s<  t t |}r rtddu r du rt s!t dsfdu r+ fddfddd}d	}t||k re|td
| gd |ttfddt	|D 7 }|d	7 }t||k s<n2d}d	}t||k rt
d }| |td
|  }	|||	|7 }|d	7 }t||k sp|d| S )a  Derive one or more keys from a password (or passphrase).

    This function performs key derivation according to the PKCS#5 standard (v2.0).

    Args:
     password (string or byte string):
        The secret password to generate the key from.
     salt (string or byte string):
        A (byte) string to use for better protection from dictionary attacks.
        This value does not need to be kept secret, but it should be randomly
        chosen for each derivation. It is recommended to use at least 16 bytes.
     dkLen (integer):
        The cumulative length of the keys to produce.

        Due to a flaw in the PBKDF2 design, you should not request more bytes
        than the ``prf`` can output. For instance, ``dkLen`` should not exceed
        20 bytes in combination with ``HMAC-SHA1``.
     count (integer):
        The number of iterations to carry out. The higher the value, the slower
        and the more secure the function becomes.

        You should find the maximum number of iterations that keeps the
        key derivation still acceptable on the slowest hardware you must support.

        Although the default value is 1000, **it is recommended to use at least
        1000000 (1 million) iterations**.
     prf (callable):
        A pseudorandom function. It must be a function that returns a
        pseudorandom byte string from two parameters: a secret and a salt.
        The slower the algorithm, the more secure the derivation function.
        If not specified, **HMAC-SHA1** is used.
     hmac_hash_module (module):
        A module from ``Cryptodome.Hash`` implementing a Merkle-Damgard cryptographic
        hash, which PBKDF2 must use in combination with HMAC.
        This parameter is mutually exclusive with ``prf``.

    Return:
        A byte string of length ``dkLen`` that can be used as key material.
        If you want multiple keys, just break up this string into segments of the desired length.
    z2'prf' and 'hmac_hash_module' are mutually exlusiveN_pbkdf2_hmac_assistc                    s   t | |  S N)r   r   r    ps)hmac_hash_moduler&   r'   <lambda>       zPBKDF2.<locals>.<lambda>c                    s(   | d  | d | d< | d< | d S )Nr   r   r&   )r.   )r!   prfr&   r'   link   s    zPBKDF2.<locals>.link    r   z>I   c                 3   s    | ]} V  qd S r+   r&   ).0j)r3   r.   r&   r'   	<genexpr>   s    zPBKDF2.<locals>.<genexpr>)r   r   r
   hasattrr   structpackr   r   ranger   r   copyupdater    r*   )
r!   r"   r#   r$   r2   r/   keyr%   baseZfirst_digestr&   )r/   r3   r!   r2   r.   r'   PBKDF2b   s6   *"rA   c                   @   s>   e Zd ZdZdddZedd Zdd Zd	d
 Zdd Z	dS )_S2VzString-to-vector PRF as defined in `RFC5297`_.

    This class implements a pseudorandom function family
    based on CMAC that takes as input a vector of strings.

    .. _RFC5297: http://tools.ietf.org/html/rfc5297
    Nc                 C   sV   t dd|| _|| _d|j  | _| _|jd d | _|du r$i | _dS t|| _dS )a  Initialize the S2V PRF.

        :Parameters:
          key : byte string
            A secret that can be used as key for CMACs
            based on ciphers from ``ciphermod``.
          ciphermod : module
            A block cipher module from `Cryptodome.Cipher`.
          cipher_params : dictionary
            A set of extra parameters to use to create a cipher instance.
        N    r   r   )	r   _key
_ciphermod
block_size_last_string_cache
_n_updates_cipher_paramsdict)selfr?   	ciphermodcipher_paramsr&   r&   r'   __init__   s   
z_S2V.__init__c                 C   s
   t | |S )a  Create a new S2V PRF.

        :Parameters:
          key : byte string
            A secret that can be used as key for CMACs
            based on ciphers from ``ciphermod``.
          ciphermod : module
            A block cipher module from `Cryptodome.Cipher`.
        )rB   )r?   rM   r&   r&   r'   r      s   
z_S2V.newc                 C   s@   t |d> }t|d d@ r|dN }t|t|t| d  S )Nr   r         )r   r   r   r   )rL   bsZdoubledr&   r&   r'   _double   s   z_S2V._doublec                 C   sd   | j dkr	td|  j d8  _ tj| j| j| j| jd}t| 	| j
| | _
tdd|| _dS )ad  Pass the next component of the vector.

        The maximum number of components you can pass is equal to the block
        length of the cipher (in bits) minus 1.

        :Parameters:
          item : byte string
            The next component of the vector.
        :Raise TypeError: when the limit on the number of components has been reached.
        r   z!Too many components passed to S2Vr   msgrM   rN   N)rI   r   r   r   rD   rG   rE   rJ   r   rS   rH   r    r   )rL   itemmacr&   r&   r'   r>      s   
z_S2V.updatec                 C   s|   t | jdkr| jdd t| jdd | j }n| jd d dd }t|| | j}tj| j|| j| j	d}|
 S )z"Derive a secret from the vector of components.

        :Return: a byte string, as long as the block length of the cipher.
        r)   Ni   s                  rT   )r   rG   r   rH   rS   r   r   rD   rE   rJ   r    )rL   finalpaddedrW   r&   r&   r'   derive   s   &z_S2V.deriver+   )
__name__
__module____qualname____doc__rO   staticmethodr   rS   r>   r[   r&   r&   r&   r'   rB      s    

rB   r   c                    s   | }|d|j  krtd|sd|j  }|du rd}tj|| |d}| }dg}	d}
d}||k rYtj||	d	 | td
|
 |d}|	|  ||j 7 }|
d7 }
||k s3d|	 |dkrh d S  fddt	d|D }t
|d| S )a  Derive one or more keys from a master secret using
    the HMAC-based KDF defined in RFC5869_.

    Args:
     master (byte string):
        The unguessable value used by the KDF to generate the other keys.
        It must be a high-entropy secret, though not necessarily uniform.
        It must not be a password.
     salt (byte string):
        A non-secret, reusable value that strengthens the randomness
        extraction step.
        Ideally, it is as long as the digest size of the chosen hash.
        If empty, a string of zeroes in used.
     key_len (integer):
        The length in bytes of every derived key.
     hashmod (module):
        A cryptographic hash algorithm from :mod:`Cryptodome.Hash`.
        :mod:`Cryptodome.Hash.SHA512` is a good choice.
     num_keys (integer):
        The number of keys to derive. Every key is :data:`key_len` bytes long.
        The maximum cumulative length of all keys is
        255 times the digest size.
     context (byte string):
        Optional identifier describing what the keys are used for.

    Return:
        A byte string or a tuple of byte strings.

    .. _RFC5869: http://tools.ietf.org/html/rfc5869
       zToo much secret data to deriverC   Nr4   )	digestmodr   r   Bc                       g | ]
} ||  qS r&   r&   r6   idxZderived_outputkey_lenr&   r'   
<listcomp>K      zHKDF.<locals>.<listcomp>)r   r   r   r   r    r:   r;   appendjoinr   list)Zmasterri   r"   Zhashmodnum_keyscontextZ
output_lenhmacZprktntlenkolr&   rh   r'   HKDF  s2    
$


rv   c                    s.  dt |d  |krtd|dkrtd|dd|  kr"tdd	d
 }t| ||d | d|d}tj}	tj}
g }t|D ]1}|d | }td| }|	|||d|   |t	d| ||
}|ritd| |t
|g7 }q?t| d|| d|d |dkr S  fddtd| D }|S )uH  Derive one or more keys from a passphrase.

    Args:
     password (string):
        The secret pass phrase to generate the keys from.
     salt (string):
        A string to use for better protection from dictionary attacks.
        This value does not need to be kept secret,
        but it should be randomly chosen for each derivation.
        It is recommended to be at least 16 bytes long.
     key_len (integer):
        The length in bytes of every derived key.
     N (integer):
        CPU/Memory cost parameter. It must be a power of 2 and less
        than :math:`2^{32}`.
     r (integer):
        Block size parameter.
     p (integer):
        Parallelization parameter.
        It must be no greater than :math:`(2^{32}-1)/(4r)`.
     num_keys (integer):
        The number of keys to derive. Every key is :data:`key_len` bytes long.
        By default, only 1 key is generated.
        The maximum cumulative length of all keys is :math:`(2^{32}-1)*32`
        (that is, 128TB).

    A good choice of parameters *(N, r , p)* was suggested
    by Colin Percival in his `presentation in 2009`__:

    - *( 2¹⁴, 8, 1 )* for interactive logins (≤100ms)
    - *( 2²⁰, 8, 1 )* for file encryption (≤5s)

    Return:
        A byte string or a tuple of byte strings.

    .. __: http://www.tarsnap.com/scrypt/scrypt-slides.pdf
    r5   r   zN must be a power of 2l        zN is too bigl    rP   zp or r are too bigc                 S   s   t | |t S r+   )r   r   r   r    r,   r&   r&   r'   r0     r1   zscrypt.<locals>.<lambda>)r2   zError %X while running scryptr4   c                    re   r&   r&   rf   Zdkri   r&   r'   rj     rk   zscrypt.<locals>.<listcomp>r   )bit_sizer   rA   _raw_scrypt_libscryptROMix_raw_salsa20_libZSalsa20_8_corer   r   r   r   rm   )r!   r"   ri   Nrr-   ro   Zprf_hmac_sha256Zstage_1rz   coreZdata_outZflowrg   Z
buffer_outresultru   r&   rw   r'   scryptQ  sD   '
r   c                    s   d}g  | D ]}t t|dd  d} t| qd   fddtdt dD }g }|d d	 D ]}t|d}|||  q9|d	 }t|ddt| > }|||  d
|}t	|S )N@./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789r5   r   r4   c                       g | ]
} ||d   qS )   r&   rf   bitsr&   r'   rj         z"_bcrypt_encode.<locals>.<listcomp>r   r   rc    )
binr   zfillrl   r	   rm   r<   r   intr   )datar.   cZbits_cbits6r   grg   r&   r   r'   _bcrypt_encode  s    


r   c           	         s   d}g  t | D ]}||}t|dd  d} | qd  t| d }|dkr3td|dkr> d d  n
|d	krH d d
   fddtdt dD }g }|D ]}|t	t
|d q[d|}|S )Nr   r5   r   r      r   zIncorrect length   c                    r   )r   r&   rf   r   r&   r'   rj     r   z"_bcrypt_decode.<locals>.<listcomp>r   r   r4   )r   findr   r   rl   rm   r   r   r<   r   r   )	r   r.   r   rg   r   Zmodulo4Zbits8r   r   r&   r   r'   _bcrypt_decode  s(   


r   c           	      C   sx   ddl m} t| dkrtdd|  krdks"td td|| |j|||}|}tdD ]}||}q2|S )	Nr   )_EKSBlowfishH   z6The password is too long. It must be 72 bytes at most.r      z-bcrypt cost factor must be in the range 4..31@   )ZCryptodome.Cipherr   r   r   r   ZMODE_ECBr<   encrypt)	r!   costr"   Zconstantinvertr   cipherctext_r&   r&   r'   _bcrypt_hash  s   r   c                 C   s   t | d} | tdd dkrtdt| dk r| d7 } |du r&td}t|dkr0td	t| ||d
d}dtt|	d }dt
| }t
|dd }d| | | S )a>  Hash a password into a key, using the OpenBSD bcrypt protocol.

    Args:
      password (byte string or string):
        The secret password or pass phrase.
        It must be at most 72 bytes long.
        It must not contain the zero byte.
        Unicode strings will be encoded as UTF-8.
      cost (integer):
        The exponential factor that makes it slower to compute the hash.
        It must be in the range 4 to 31.
        A value of at least 12 is recommended.
      salt (byte string):
        Optional. Random byte string to thwarts dictionary and rainbow table
        attacks. It must be 16 bytes long.
        If not passed, a random value is generated.

    Return (byte string):
        The bcrypt hash

    Raises:
        ValueError: if password is longer than 72 bytes or if it contains the zero byte

   zutf-8r   rc   z#The password contains the zero byter   rC   Nr)   z!bcrypt salt must be 16 bytes longs   OrpheanBeholderScryDoubtT   $r5   s   $2a)r   r   r   r   r   r   r   r	   strr   r   )r!   r   r"   r   Zcost_encZsalt_encZhash_encr&   r&   r'   bcrypt  s   
r   c           
      C   s   t |}t|dkrtdt| |dd dkrtdtd}||}|s.tdt|d	}d|  krBd
ksGtd tdt|d}t	| ||}t
d}tjd||d }tjd||d }	||	krttddS )a  Verify if the provided password matches the given bcrypt hash.

    Args:
      password (byte string or string):
        The secret password or pass phrase to test.
        It must be at most 72 bytes long.
        It must not contain the zero byte.
        Unicode strings will be encoded as UTF-8.
      bcrypt_hash (byte string, bytearray):
        The reference bcrypt hash the password needs to be checked against.

    Raises:
        ValueError: if the password does not match
    <   z;Incorrect length of the bcrypt hash: %d bytes instead of 60Nr   s   $2a$zUnsupported prefixs@   \$2a\$([0-9][0-9])\$([A-Za-z0-9./]{22,22})([A-Za-z0-9./]{31,31})zIncorrect bcrypt hash formatr   r   zIncorrect costr5   r)      )Zdigest_bitsr?   r   zIncorrect bcrypt hash)r   r   r   recompilematchr   groupr   r   r   r   r   r    )
r!   Zbcrypt_hashr-   r}   r   r"   Zbcrypt_hash2secretZmac1Zmac2r&   r&   r'   bcrypt_check  s,   

r   )r   N)r)   r   NN)r   N)r   r+   )-r   r:   	functoolsr   ZCryptodome.Util.py3compatr   r   r   r   r   r   r	   ZCryptodome.Hashr
   r   r   r   r   ZCryptodome.Util.strxorr   ZCryptodome.Randomr   ZCryptodome.Util.numberr   rx   r   r   ZCryptodome.Util._raw_apir   r   r   r   r{   ry   r(   rA   objectrB   rv   r   r   r   r   r   r   r&   r&   r&   r'   <module>   s2   $

+Q
`
>P
/