U +MbuM@sddlZddlZddlmZddlmZmZmZmZm Z m Z m Z ddl m Z mZmZmZmZddlmZddlmZddlmZmZmZddlmZmZmZmZed d Z ed d Z!d$ddZ"d%ddZ#Gddde$Z%d&ddZ&d'ddZ'ddZ(ddZ)ddZ*d(d d!Z+d"d#Z,dS))N)reduce)tobytesbord _copy_bytes iter_rangetostrbchrbstr)SHA1SHA256HMACCMACBLAKE2s)strxor)get_random_bytes)size long_to_bytes bytes_to_long)load_pycryptodome_raw_libcreate_string_bufferget_raw_bufferc_size_tzCrypto.Cipher._Salsa20z int Salsa20_8_core(const uint8_t *x, const uint8_t *y, uint8_t *out); zCrypto.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); cCs|st}t|}|||}|j}||kr8td|t|dkrTtdt|t|dD]}||}q`|d|S)aMDerive 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 `_. 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:`Crypto.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:`Crypto.Hash` package. The digest length must be no shorter than ``dkLen``. The default algorithm is :mod:`Crypto.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 rnew digest_size TypeErrorlen ValueErrorrdigest)passwordsaltdkLencountZhashAlgoZpHashr ir&:/tmp/pip-target-t616c12r/lib/python/Crypto/Protocol/KDF.pyPBKDF17s  r(c s*tt|}r r tddkr4dkr4tsBtdsˆdkrVfddfddd}d }t||kr|td |gd |ttfd d t |D7}|d 7}qln\d}d }t||krt d}| |td |} ||| |7}|d 7}q|d|S)aDerive 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 ``Crypto.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_assistcst||SN)r rr ps)hmac_hash_moduler&r'zPBKDF2..cs(|d|d|d<|d<|dS)Nrrr&)r.)r!prfr&r'links zPBKDF2..linkr1rz>Ic3s|]}VqdSr+r&).0j)r3r.r&r' szPBKDF2..)rrr hasattrrstructpackrrranger rcopyupdater r*) r!r"r#r$r2r/keyr%baseZ first_digestr&)r/r3r!r2r.r'PBKDF2bs0*  "  r@c@s>eZdZdZd ddZeddZddZd d Zd d Z dS)_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 NcCsTtdd||_||_d|j|_|_|jdd|_|dkrFi|_n t||_dS)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 `Crypto.Cipher`. cipher_params : dictionary A set of extra parameters to use to create a cipher instance. Nrr) r_key _ciphermod block_size _last_string_cache _n_updates_cipher_paramsdict)selfr> ciphermod cipher_paramsr&r&r'__init__s z _S2V.__init__cCs 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 `Crypto.Cipher`. )rA)r>rLr&r&r'rs z_S2V.newcCs@t|d>}t|dd@r$|dN}t|t|t| dS)Nrr)rrrr)rKbsZdoubledr&r&r'_doubles z _S2V._doublecCsd|jdkrtd|jd8_tj|j|j|j|jd}t| |j | |_ t dd||_dS)adPass 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. rz!Too many components passed to S2VrmsgrLrMN) rHrr rrCrFrDrIrrRrGr r)rKitemmacr&r&r'r=s z _S2V.updatecCs|t|jdkr4|jddt|jdd|j}n(|jdddd}t|||j}tj|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)NisrS) rrFrrGrRr rrCrDrIr )rKfinalpaddedrVr&r&r'derives&z _S2V.derive)N) __name__ __module__ __qualname____doc__rN staticmethodrrRr=rZr&r&r&r'rAs  rArc s|}|d|jkrtd|s,d|j}|dkr8d}tj|||d}|}dg} d} d} | |krtj|| d |td | |d}| || |j7} | d7} q^d| |dkrʈdSfd d t d|D} t | d|S) aDerive 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:`Crypto.Hash`. :mod:`Crypto.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 zToo much secret data to deriverBNr1) digestmodrrBcsg|]}||qSr&r&r5idxZderived_outputkey_lenr&r' KszHKDF..) rrr rr r9r:appendjoinrlist) Zmasterrgr"Zhashmodnum_keyscontextZ output_lenhmacZprktntlenkolr&rfr'HKDFs0  $      rscs0dt|d|krtd|dkr,td|dd|krDtdd d }t|||d|d|d }tj} tj} g} t|D]b} | d|} td|}| || | d||t d||| }|rtd || t |g7} q~t|d | |d|d |dkr Sfddtd|D}|S)uHDerive 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 r4rzN must be a power of 2lz N is too biglrOzp or r are too bigcSst||tSr+)r rr r r,r&r&r'r0r1zscrypt..)r2zError %X while running scryptr1csg|]}||qSr&r&rdZdkrgr&r'rhszscrypt..r) bit_sizerr@_raw_scrypt_lib scryptROMix_raw_salsa20_libZSalsa20_8_corerrrrrj)r!r"rgNrr-rlZprf_hmac_sha256Zstage_1rwcoreZdata_outZflowreZ buffer_outresultrrr&rtr'scryptQsF'       r}csd}g|D],}tt|ddd}t|q dfddtdtdD}g}|dd D]}t|d}|||qr|d }t|ddt|>}|||d |}t |S) N@./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789r4rr1csg|]}||dqS)r&rdbitsr&r'rhsz"_bcrypt_encode..rrrb) binrzfillrir rjr;rintr)datar.cZbits_cbits6r|grer&rr'_bcrypt_encodes    rc sd}gt|D].}||}t|ddd}|qdt|d}|dkrhtdn*|dkr~ddn|d krdd fd d td tdD}g}|D]}|t t |dqd|}|S)Nr~r4rrrzIncorrect lengthcsg|]}||dqS)rr&rdrr&r'rhsz"_bcrypt_decode..rrr1) rfindrrrirjrrr;rr) rr.rrerZmodulo4Zbits8r|rr&rr'_bcrypt_decodes(        rc Csrddlm}t|dkr tdd|kr4dks>ntd|||j|||}|}tdD]}||}q^|S) Nr) _EKSBlowfishHz6The password is too long. It must be 72 bytes at most.rz-bcrypt cost factor must be in the range 4..31@)Z Crypto.CipherrrrrZMODE_ECBr;encrypt) r!costr"Zconstantinvertrcipherctext_r&r&r' _bcrypt_hashs    rcCst|d}|tdddkr(tdt|dkr<|d7}|dkrLtd}t|dkr`td t|||d d }d tt| d }d t |}t |dd}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 zutf-8rrbz#The password contains the zero byterrBNr)z!bcrypt salt must be 16 bytes longsOrpheanBeholderScryDoubtT$r4s$2a) rrrrrrrr strrr)r!rr"rZcost_encZsalt_encZhash_encr&r&r'bcrypts    rc Cst|}t|dkr$tdt||dddkrrzIncorrect bcrypt hash)rrrrecompilematchrgrouprrrrrr ) r!Z bcrypt_hashr-rzrr"Z bcrypt_hash2secretZmac1Zmac2r&r&r' bcrypt_checks&    r)rN)r)rNN)rN)r)N)-rr9 functoolsrZCrypto.Util.py3compatrrrrrrr Z Crypto.Hashr r r r rZCrypto.Util.strxorrZ Crypto.RandomrZCrypto.Util.numberrrurrZCrypto.Util._raw_apirrrrrxrvr(r@objectrArsr}rrrrrr&r&r&r's0 $   + Q` > P /