B d>@sFdZddlZddlZddlZddlZddlmZddlmZm Z m Z m Z dddd d d d Z ej ejejejejejd Zejd kre ddddeejejejdGdddeZGdddeZGdddeZeeedddZeeedddZ ee j!edddZ"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/d0d1Z,ej-eej*fe%ed2d3d4Z.ee%d5d6d7Z/dd"d(d+dddgZ0e1d8krBe2d9ddl3Z3xFe4d:D]:Z5e36\Z7Z8e7rPe5d;dkre5re2dabFunctions 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 transformcorekeys0 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__rr0/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_lengthreturncCs|d}t|}||kr(td||fd}||d}xFt||kr~|t|}t|d}|dd}||d|}q:Wt||kstdd|d|gS) 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 %ir Ns)len OverflowErrorosurandomreplaceAssertionErrorjoin)rr max_msglength msglengthpaddingpadding_lengthZ needed_bytesZ new_paddingrrr_pad_for_encryptionTs"    r&cCsJ|d}t|}||kr(td||f||d}dd|dd|gS)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 rsr)rrr!)rrr"r#r%rrr_pad_for_signings  r()rpub_keyrcCsBt|j}t||}t|}t||j|j}t ||}|S)aEncrypts 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_sizenr&r bytes2intrZ encrypt_inte int2bytes)rr) keylengthpaddedpayload encryptedblockrrrencrypts     r4)cryptopriv_keyrc Cst|j}t|}||}t||}t||kr@tdt |ddd }| dd}|dk}||B} | r|td||ddS)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 failedNsr r) rr*r+rr,Zblinded_decryptr.rrrfind) r5r6 blocksizer2 decrypted cleartextZcleartext_marker_badZsep_idxZ sep_idx_badZ anything_badrrrdecrypts3      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)aSigns 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_hashrrrsign8s rE)r signaturer)rc Cst|j}t|}t||j|j}t||}t |}t ||}t ||} t | |} t ||krptd| |krtd|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<expectedrrrverifyNs       rL)rFr)rcCs<t|j}t|}t||j|j}t||}t |S)aReturns 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;rIrrrfind_signature_hashts   rM)infiler:rccs6x0||}t|}|dkrP|V||krPqWdS)zGenerator, 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_bytesrrryield_fixedblockss rQ)rrJrcCsx|tkrtd|t|}|}t|tr8||n8t|drNt|jdsRtxt|dD]}||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 isinstancebytesupdatehasattrrOr rQdigest)rrJmethodZhasherr3rrrrDs    rD)rIrcCs.x tD]\}}||kr |Sq WtddS)zFinds 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)rIZhashnamerBrrrrHsrH__main__z'Running doctests 1000x or until failureidz%i timesz Doctests done)9rhashlibrsystypinghmacrrrrrr@md5sha1sha224sha256sha384sha512rS version_inforVsha3_256sha3_384sha3_512 Exceptionr rrrUintr&r(Z PublicKeyr4Z PrivateKeyr=strrCrErLrMBinaryIOIteratorrQUnionrDrH__all__r printdoctestrangecounttestmodZfailurestestsrrrrsj     ." S!&