wec@sddlZddlZddlmZddlmZmZmZmZm Z m Z m Z ddl m Z mZmZmZmZddlmZddlmZddlmZmZmZddlmZmZmZmZed d Z ed d Z!d ddZ#dd dddZ$de%fdYZ&dddZ'ddZ(dZ)dZ*dZ+ddZ,dZ-ddddZ.dS(iN(treduce(ttobytestbordt _copy_bytest iter_rangettostrtbchrtbstr(tSHA1tSHA256tHMACtCMACtBLAKE2s(tstrxor(tget_random_bytes(tsizet long_to_bytest bytes_to_long(tload_pycryptodome_raw_libtcreate_string_buffertget_raw_buffertc_size_tsCrypto.Cipher._Salsa20s int Salsa20_8_core(const uint8_t *x, const uint8_t *y, uint8_t *out); sCrypto.Protocol._scrypts  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); icCs|st}nt|}|j||}|j}||krVtd|nt|dkrtdt|nx-t|dD]}|j|j}qW|j| S(sMDerive 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. s:Selected hash algorithm has a too short digest (%d bytes).is,Salt is not 8 bytes long (%d bytes instead).i( RRtnewt digest_sizet TypeErrortlent ValueErrorRtdigest(tpasswordtsalttdkLentcountthashAlgotpHashRti((s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pytPBKDF17s    ic stt|}r3r3tdnd krTd krTtnsjtd rd krfdnfdd}d}xt||kr|tjd|gd|tt fd t |D7}|d7}qWnd}d}xvt||krt j d}|j j|tjd|j} ||j| |7}|d7}q-W|| S( sDerive 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. Strings will be encoded as ISO 8859-1 (also known as Latin-1), which does not allow any characters with codepoints > 255. 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. Strings will be encoded as ISO 8859-1 (also known as Latin-1), which does not allow any characters with codepoints > 255. 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. s2'prf' and 'hmac_hash_module' are mutually exlusivet_pbkdf2_hmac_assistcstj||jS(N(R RR(tpts(thmac_hash_module(s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pytscs.|d|d|d<|d<|dS(Nii((R&(Rtprf(s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pytlinks&tis>Iic3s|]}VqdS(N((t.0tj(R*R&(s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pys sN(RRtNoneRthasattrRtstructtpackRR trangeR RtcopytupdateRR$( RRRRR)R'tkeyR"tbaset first_digest((R'R*RR)R&s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pytPBKDF2bs00     &,+t_S2VcBsDeZdZddZedZdZdZdZ RS(sString-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 cCsttdd||_||_d|j|_|_|jdd|_|dkrai|_nt ||_dS(s~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. tiiN( RR.t_keyt _ciphermodt block_sizet _last_stringt_cachet _n_updatest_cipher_paramstdict(tselfR5t ciphermodt cipher_params((s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pyt__init__s    cCs t||S(s 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`. (R9(R5RD((s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pyRs cCsOt|d>}t|dd@r1|dN}nt|t|t| S(Niiii(RRRR(RCtbstdoubled((s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pyt_doubles cCs|jdkrtdn|jd8_tj|jd|jd|jd|j}t|j |j |j |_ t dd||_dS(sdPass 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. is!Too many components passed to S2VitmsgRDREN(R@RR RR;R>R<RAR RIR?RRR.(RCtitemtmac((s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pyR4s    $cCst|jdkr<|jd t|jd|j}n0|jdd d }t||j|j}tj|jd|d|jd|j }|j S( s"Derive a secret from the vector of components. :Return: a byte string, as long as the block length of the cipher. iisR:iRJRDREt( RR>R R?RIR RR;R<RAR(RCtfinaltpaddedRL((s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pytderives'  N( t__name__t __module__t__doc__R.RFt staticmethodRRIR4RP(((s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pyR9s    icCs^||}|d|jkr,tdn|sBd|j}n|d krWd}ntj||d|}|j}dg} d} d} xj| |krtj|| d|tjd | d|}| j|j| |j7} | d7} qWdj | } |dkr | | Sgt d||D]} | | | |!^q3}t || S( sDerive 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. key_len (integer): The length in bytes of every derived key. 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. 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 isToo much secret data to deriveR:R+t digestmodiiitBN( RRR.R RRR0R1tappendtjoinRtlist(tmastertkey_lenRthashmodtnum_keystcontextt output_lenthmactprktttnttlentderived_outputtidxtkol((s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pytHKDFs.     0  -cCsdt|d|kr)tdn|d krDtdn|dd|krgtdnd}t|||d|dd |}tj} tj} g} xt|D]} | d|} td|}| || | d|!|t d||| }|r&td |n| t |g7} qWt|d j | ||dd |}|dkru|Sgtd |||D]} || | |!^q}|S(sGDerive 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 each 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 iisN must be a power of 2i s N is too bigisp or r are too bigcSstj||tjS(N(R RR R(R%R&((s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pyR(sR)sError %X while running scryptR+iIIII( tbit_sizeRR8t_raw_scrypt_libt scryptROMixt_raw_salsa20_libtSalsa20_8_coreRRRRRX(RRR[tNtrR%R]tprf_hmac_sha256tstage_1Rktcoretdata_outtflowRft buffer_outtresulttdkRg((s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pytscryptWs>'  #        1c Cs d}g}x@|D]8}tt|djd}|jt|qWdj|}gtdt|dD]}|||d!^qw}g}x2|d D]&}t|d}|j||qW|d}t|ddt|>}|j||dj|}t |S(Ns@./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789iiR+iii( tbinRtzfillRWRRXR2RtintR( tdataR&tbitstctbits_cRftbits6Rvtg((s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pyt_bcrypt_encodes  6 c Cs@d}g}xIt|D];}|j|}t|djd}|j|qWdj|}t|d}|dkrtdn2|dkr|d }n|d kr|d }ngtd t|d D]}|||d !^q}g}x*|D]"} |jt t | dqWdj|}|S( Ns@./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789iiR+iisIncorrect lengthiiiii( RtfindRyRzRWRXRRR2RR{( R|R&R}R~RfRtmodulo4tbits8RvR((s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pyt_bcrypt_decodes(     6  c Csddlm}t|dkr1tdnd|koHdkns\tdn|j||j|||}|}x#tdD]}|j|}qW|S( Ni(t _EKSBlowfishiHs6The password is too long. It must be 72 bytes at most.iis-bcrypt cost factor must be in the range 4..31i@(t Crypto.CipherRRRRtMODE_ECBR2tencrypt( RtcostRtconstanttinvertRtciphertctextt_((s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pyt _bcrypt_hashscCst|d}|jtdddkr=tdnt|dkr\|d7}n|d krwtd}nt|dkrtdnt|||d t}d t t |j d }d t |}t |d }d |||S(s>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 sutf-8iis#The password contains the zero byteiHR:is!bcrypt salt must be 16 bytes longtOrpheanBeholderScryDoubtt$is$2aN( RRRRRR.RRtTrueRtstrRzR(RRRRtcost_enctsalt_encthash_enc((s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pytbcrypts  c Csct|}t|dkr7tdt|n|d dkrVtdntjd}|j|}|stdnt|jd}d|kod knstd nt|jd }t |||}t d }t j d dd|d|j }t j d dd|d|j } || kr_tdndS(sVerify 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 i<s;Incorrect length of the bcrypt hash: %d bytes instead of 60is$2a$sUnsupported prefixs@\$2a\$([0-9][0-9])\$([A-Za-z0-9./]{22,22})([A-Za-z0-9./]{31,31})sIncorrect bcrypt hash formatiisIncorrect costiit digest_bitsiR5R|sIncorrect bcrypt hashN(RRRtretcompiletmatchR{tgroupRRRR RR( Rt bcrypt_hashR%RoRRt bcrypt_hash2tsecrettmac1tmac2((s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pyt bcrypt_checks&  $$ R+c CsF|d krd}n|jddkr9tdn|jddkr]tdnt||dd}||}d}d} xmt| |krt|d|d||} | ||| 7} |d7}|d krtd qqW|dkr| | Sgtd ||D]} | | | |!^q!} | Sd S( sJDerive one or more keys from a master secret using a pseudorandom function in Counter Mode, as specified in `NIST SP 800-108r1 `_. Args: master (byte string): The secret value used by the KDF to derive the other keys. It must not be a password. The length on the secret must be consistent with the input expected by the :data:`prf` function. key_len (integer): The length in bytes of each derived key. prf (function): A pseudorandom function that takes two byte strings as parameters: the secret and an input. It returns another byte string. num_keys (integer): The number of keys to derive. Every key is :data:`key_len` bytes long. By default, only 1 key is derived. label (byte string): Optional description of the purpose of the derived keys. It must not contain zero bytes. context (byte string): Optional information pertaining to the protocol that uses the keys, such as the identity of the participants, nonces, session IDs, etc. It must not contain zero bytes. Return: - a byte string (if ``num_keys`` is not specified), or - a tuple of byte strings (if ``num_key`` is specified). iR:isNull byte found in labelsNull byte found in contextiiR+IsOverflow in SP800 108 counteriN(R.RRRRR( RZR[R)R]tlabelR^t key_len_encR_R"RwtinfoRfRg((s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pytSP800_108_CounterGs*!      -(/RR0t functoolsRtCrypto.Util.py3compatRRRRRRRt Crypto.HashRR R R R tCrypto.Util.strxorR t Crypto.RandomRtCrypto.Util.numberRRiRRtCrypto.Util._raw_apiRRRRRlRjR.R#R8tobjectR9RhRxRRRRRR(((s9/usr/lib64/python2.7/site-packages/Crypto/Protocol/KDF.pyts.  4("  +W`> P    / -