B Ðñ¢d®>ã@sFdZddlZddlZddlZddlZddlmZddlmZm Z m Z m Z dddd d d d œZ ej ejejejejejd œZejd kr¬e  ddddœ¡e ejejejdœ¡Gdd„deƒZGdd„deƒZGdd„deƒZeeedœdd„Zeeedœdd„Z ee j!edœdd„Z"ee j#ed œd!d"„Z$ee j#e%ed#œd$d%„Z&ee j#e%ed&œd'd(„Z'eee j!e%d)œd*d+„Z(ee j!e%d,œd-d.„Z)ej*eej+ed/œd0d1„Z,ej-eej*fe%ed2œd3d4„Z.ee%d5œd6d7„Z/dd"d(d+dddgZ0e1d8k�rBe2d9ƒddl3Z3xFe4d:ƒD]:Z5e3 6¡\Z7Z8e7�rPe5d;dk�rüe5�rüe2dabFunctions for PKCS#1 version 1.5 encryption and signing This module implements certain functionality from PKCS#1 version 1.5. For a very clear example, read http://www.di-mgt.com.au/rsa_alg.html#pkcs1schemes At least 8 bytes of random padding is used when encrypting a message. This makes these methods much more secure than the ones in the ``rsa`` module. WARNING: this module leaks information when decryption fails. The exceptions that are raised contain the Python traceback information, which can be used to deduce where in the process the failure occurred. DO NOT PASS SUCH INFORMATION to your users. éN)Úcompare_digesté)ÚcommonÚ transformÚcoreÚkeys0 0 *†H†÷ s0!0 +s0-0  `†Hes010  `†He s0A0  `†He0s0Q0  `†He@)ÚMD5zSHA-1zSHA-224zSHA-256zSHA-384zSHA-512)éés010  `†He s0A0  `†He 0s0Q0  `†He @)zSHA3-256zSHA3-384zSHA3-512c@seZdZdZdS)Ú CryptoErrorz-Base class for all exceptions in this module.N)Ú__name__Ú __module__Ú __qualname__Ú__doc__©rrú0/tmp/pip-target-jj3kjtpb/lib/python/rsa/pkcs1.pyr Hsr c@seZdZdZdS)ÚDecryptionErrorzRaised when decryption fails.N)r r rrrrrrrLsrc@seZdZdZdS)ÚVerificationErrorzRaised when verification fails.N)r r rrrrrrrPsr)ÚmessageÚ target_lengthÚreturncCs¢|d}t|ƒ}||kr(td||fƒ‚d}||d}xFt|ƒ|kr~|t|ƒ}t |d¡}| dd¡}||d|…}q:Wt|ƒ|ks�t‚d d|d|g¡S) aPads the message for encryption, returning the padded message. :return: 00 02 RANDOM_DATA 00 MESSAGE >>> block = _pad_for_encryption(b'hello', 16) >>> len(block) 16 >>> block[0:2] b'\x00\x02' >>> block[-6:] b'\x00hello' é z;%i bytes needed for message, but there is only space for %iór éóNs)ÚlenÚ OverflowErrorÚosÚurandomÚreplaceÚAssertionErrorÚjoin)rrÚ max_msglengthÚ msglengthÚpaddingÚpadding_lengthZ needed_bytesZ new_paddingrrrÚ_pad_for_encryptionTs"    r&cCsJ|d}t|ƒ}||kr(td||fƒ‚||d}d d|dd|g¡S)ajPads the message for signing, returning the padded message. The padding is always a repetition of FF bytes. :return: 00 01 PADDING 00 MESSAGE >>> block = _pad_for_signing(b'hello', 16) >>> len(block) 16 >>> block[0:2] b'\x00\x01' >>> block[-6:] b'\x00hello' >>> block[2:-6] b'\xff\xff\xff\xff\xff\xff\xff\xff' rz;%i bytes needed for message, but there is only space for %ir rsóÿr)rrr!)rrr"r#r%rrrÚ_pad_for_signing‚s  r()rÚpub_keyrcCsBt |j¡}t||ƒ}t |¡}t ||j|j¡}t  ||¡}|S)aÂEncrypts the given message using PKCS#1 v1.5 :param message: the message to encrypt. Must be a byte string no longer than ``k-11`` bytes, where ``k`` is the number of bytes needed to encode the ``n`` component of the public key. :param pub_key: the :py:class:`rsa.PublicKey` to encrypt with. :raise OverflowError: when the message is too large to fit in the padded block. >>> from rsa import key, common >>> (pub_key, priv_key) = key.newkeys(256) >>> message = b'hello' >>> crypto = encrypt(message, pub_key) The crypto text should be just as long as the public key 'n' component: >>> len(crypto) == common.byte_size(pub_key.n) True ) rÚ byte_sizeÚnr&rÚ bytes2intrZ encrypt_intÚeÚ int2bytes)rr)Ú keylengthÚpaddedÚpayloadÚ encryptedÚblockrrrÚencrypt¤s     r4)ÚcryptoÚpriv_keyrc CsŒt |j¡}t |¡}| |¡}t ||¡}t|ƒ|kr@tdƒ‚t |dd…dƒ }|  dd¡}|dk}||B} | r|tdƒ‚||dd…S)aaDecrypts the given message using PKCS#1 v1.5 The decryption is considered 'failed' when the resulting cleartext doesn't start with the bytes 00 02, or when the 00 byte between the padding and the message cannot be found. :param crypto: the crypto text as returned by :py:func:`rsa.encrypt` :param priv_key: the :py:class:`rsa.PrivateKey` to decrypt with. :raise DecryptionError: when the decryption fails. No details are given as to why the code thinks the decryption fails, as this would leak information about the private key. >>> import rsa >>> (pub_key, priv_key) = rsa.newkeys(256) It works with strings: >>> crypto = encrypt(b'hello', pub_key) >>> decrypt(crypto, priv_key) b'hello' And with binary data: >>> crypto = encrypt(b'\x00\x00\x00\x00\x01', pub_key) >>> decrypt(crypto, priv_key) b'\x00\x00\x00\x00\x01' Altering the encrypted information will *likely* cause a :py:class:`rsa.pkcs1.DecryptionError`. If you want to be *sure*, use :py:func:`rsa.sign`. .. warning:: Never display the stack trace of a :py:class:`rsa.pkcs1.DecryptionError` exception. It shows where in the code the exception occurred, and thus leaks information about the key. It's only a tiny bit of information, but every bit makes cracking the keys easier. >>> crypto = encrypt(b'hello', pub_key) >>> crypto = crypto[0:5] + b'X' + crypto[6:] # change a byte >>> decrypt(crypto, priv_key) Traceback (most recent call last): ... rsa.pkcs1.DecryptionError: Decryption failed zDecryption failedNésré r) rr*r+rr,Zblinded_decryptr.rrrÚfind) r5r6Ú blocksizer2Ú decryptedÚ cleartextZcleartext_marker_badZsep_idxZ sep_idx_badZ anything_badrrrÚdecryptÄs3      r=)Ú hash_valuer6Ú hash_methodrc Cs^|tkrtd|ƒ‚t|}||}t |j¡}t||ƒ}t |¡}| |¡}t  ||¡} | S)abSigns a precomputed hash with the private key. Hashes the message, then signs the hash with the given key. This is known as a "detached signature", because the message itself isn't altered. :param hash_value: A precomputed hash to sign (ignores message). :param priv_key: the :py:class:`rsa.PrivateKey` to sign with :param hash_method: the hash method used on the message. Use 'MD5', 'SHA-1', 'SHA-224', SHA-256', 'SHA-384' or 'SHA-512'. :return: a message signature block. :raise OverflowError: if the private key is too small to contain the requested hash. zInvalid hash method: %s) Ú HASH_ASN1Ú ValueErrorrr*r+r(rr,Zblinded_encryptr.) r>r6r?Úasn1coder<r/r0r1r2r3rrrÚ sign_hashs      rC)rr6r?rcCst||ƒ}t|||ƒS)aÍSigns the message with the private key. Hashes the message, then signs the hash with the given key. This is known as a "detached signature", because the message itself isn't altered. :param message: the message to sign. Can be an 8-bit string or a file-like object. If ``message`` has a ``read()`` method, it is assumed to be a file-like object. :param priv_key: the :py:class:`rsa.PrivateKey` to sign with :param hash_method: the hash method used on the message. Use 'MD5', 'SHA-1', 'SHA-224', SHA-256', 'SHA-384' or 'SHA-512'. :return: a message signature block. :raise OverflowError: if the private key is too small to contain the requested hash. )Ú compute_hashrC)rr6r?Zmsg_hashrrrÚsign8s rE)rÚ signaturer)rc Cs„t |j¡}t |¡}t ||j|j¡}t ||¡}t |ƒ}t ||ƒ}t ||} t | |ƒ} t |ƒ|krptdƒ‚| |kr€tdƒ‚|S)aJVerifies that the signature matches the message. The hash method is detected automatically from the signature. :param message: the signed message. Can be an 8-bit string or a file-like object. If ``message`` has a ``read()`` method, it is assumed to be a file-like object. :param signature: the signature block, as created with :py:func:`rsa.sign`. :param pub_key: the :py:class:`rsa.PublicKey` of the person signing the message. :raise VerificationError: when the signature doesn't match the message. :returns: the name of the used hash. zVerification failed)rr*r+rr,rÚ decrypt_intr-r.Ú_find_method_hashrDr@r(rr) rrFr)r/r2r;ÚclearsigÚ method_nameZ message_hashr<ÚexpectedrrrÚverifyNs       rL)rFr)rcCs<t |j¡}t |¡}t ||j|j¡}t ||¡}t |ƒS)a‡Returns the hash name detected from the signature. If you also want to verify the message, use :py:func:`rsa.verify()` instead. It also returns the name of the used hash. :param signature: the signature block, as created with :py:func:`rsa.sign`. :param pub_key: the :py:class:`rsa.PublicKey` of the person signing the message. :returns: the name of the used hash. ) rr*r+rr,rrGr-r.rH)rFr)r/r2r;rIrrrÚfind_signature_hashts   rM)Úinfiler:rccs6x0| |¡}t|ƒ}|dkrP|V||krPqWdS)zðGenerator, yields each block of ``blocksize`` bytes in the input file. :param infile: file to read and separate in blocks. :param blocksize: block size in bytes. :returns: a generator that yields the contents of each block rN)Úreadr)rNr:r3Ú read_bytesrrrÚyield_fixedblocks‡s rQ)rrJrcCsx|tkrtd|ƒ‚t|}|ƒ}t|tƒr8| |¡n8t|dƒrNt|jdƒsRt‚xt|dƒD]}| |¡q^W|  ¡S)a4Returns the message digest. :param message: the signed message. Can be an 8-bit string or a file-like object. If ``message`` has a ``read()`` method, it is assumed to be a file-like object. :param method_name: the hash method, must be a key of :py:const:`HASH_METHODS`. zInvalid hash method: %srOÚ__call__i) Ú HASH_METHODSrAÚ isinstanceÚbytesÚupdateÚhasattrrOr rQÚdigest)rrJÚmethodZhasherr3rrrrDœs    rD)rIrcCs.x t ¡D]\}}||kr |Sq Wtdƒ‚dS)z³Finds the hash method. :param clearsig: full padded ASN1 and hash. :return: the used hash method. :raise VerificationFailed: when the hash method cannot be found zVerification failedN)r@Úitemsr)rIZhashnamerBrrrrH¸srHÚ__main__z'Running doctests 1000x or until failureièédz%i timesz Doctests done)9rÚhashlibrÚsysÚtypingÚhmacrÚrrrrr@Úmd5Úsha1Úsha224Úsha256Úsha384Úsha512rSÚ version_inforVÚsha3_256Úsha3_384Úsha3_512Ú Exceptionr rrrUÚintr&r(Z PublicKeyr4Z PrivateKeyr=ÚstrrCrErLrMÚBinaryIOÚIteratorrQÚUnionrDrHÚ__all__r ÚprintÚdoctestÚrangeÚcountÚtestmodZfailuresÚtestsrrrrÚsj     ." S!&