o
    e2A                     @   s  U d Z ddlZddlZddlZddlZddlmZ ddlmZm	Z	m
Z
mZ ejr,ejZnejZdddd	d
ddZejejejejejejdZejeejg ef f ed< 	 ejdkrpedddd eejejej d G dd de!Z"G dd de"Z#G dd de"Z$de%de&de%fddZ'de%de&de%fddZ(de%d ej)de%fd!d"Z*d#e%d$ej+de%fd%d&Z,d'e%d$ej+d(ede%fd)d*Z-de%d$ej+d(ede%fd+d,Z.de%d-e%d ej)defd.d/Z/d-e%d ej)defd0d1Z0d2ej1d3e&dej2e% fd4d5Z3dej4e%ej1f d6ede%fd7d8Z5d9e%defd:d;Z6g d<Z7e8d=krOe9d> ddl:Z:e;d?D ]Z<e:= \Z>Z?e>r7 ne<d@ dkrGe<rGe9dAe<  q*e9dB dS dS )Cab  Functions 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keys   0 0*H s   0!0	+ s   0-0	`He s   010	`He  s   0A0	`He 0s   0Q0	`He @)MD5zSHA-1zSHA-224zSHA-256zSHA-384zSHA-512HASH_METHODS)      s   010	`He  s   0A0	`He	 0s   0Q0	`He
 @)zSHA3-256zSHA3-384zSHA3-512c                   @      e Zd ZdZdS )CryptoErrorz-Base class for all exceptions in this module.N__name__
__module____qualname____doc__ r   r   4/usr/local/lib/python3.10/dist-packages/rsa/pkcs1.pyr   R       r   c                   @   r   )DecryptionErrorzRaised when decryption fails.Nr   r   r   r   r   r   V   r   r   c                   @   r   )VerificationErrorzRaised when verification fails.Nr   r   r   r   r   r   Z   r   r   messagetarget_lengthreturnc                 C   s   |d }t | }||krtd||f d}|| d }t ||k rC|t | }t|d }|dd}||d|  }t ||k s"t ||ksKJ dd|d| gS )	a  Pads 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'

       ;%i bytes needed for message, but there is only space for %i    r
          N    )lenOverflowErrorosurandomreplacejoin)r   r   max_msglength	msglengthpaddingpadding_lengthneeded_bytesnew_paddingr   r   r   _pad_for_encryption^   s$   
r-   c                 C   sJ   |d }t | }||krtd||f || d }dd|d d| gS )aj  Pads 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'

    r   r   r
   r   s       r   )r!   r"   r&   )r   r   r'   r(   r*   r   r   r   _pad_for_signing   s   r/   pub_keyc                 C   sB   t |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   	bytes2intr   encrypt_inte	int2bytes)r   r0   	keylengthpaddedpayload	encryptedblockr   r   r   encrypt   s   

r<   cryptopriv_keyc           
      C   s   t |j}t| }||}t||}t| |kr tdt	|dd d }|
dd}|dk }||B }	|	r>td||d d S )aa  Decrypts 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

    zDecryption failedN   r    r   
   r   )r   r1   r2   r   r3   blinded_decryptr6   r!   r   r   find)
r=   r>   	blocksizer:   	decrypted	cleartextcleartext_marker_badsep_idxsep_idx_badanything_badr   r   r   decrypt   s   3

rJ   
hash_valuehash_methodc           
      C   s^   |t vr
td| t | }||  }t|j}t||}t|}||}t	||}	|	S )ab  Signs 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.

    Invalid hash method: %s)
	HASH_ASN1
ValueErrorr   r1   r2   r/   r   r3   blinded_encryptr6   )
rK   r>   rL   asn1coderE   r7   r8   r9   r:   r;   r   r   r   	sign_hash  s   


rR   c                 C   s   t | |}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_hashrR   )r   r>   rL   msg_hashr   r   r   sign@  s   
rU   	signaturec                 C   s   t |j}t|}t||j|j}t||}t	|}t
| |}t| | }	t|	|}
t||kr8td|
|kr@td|S )aJ  Verifies 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.

    Verification failed)r   r1   r2   r   r3   r   decrypt_intr5   r6   _find_method_hashrS   rN   r/   r!   r   )r   rV   r0   r7   r:   rD   clearsigmethod_namemessage_hashrE   expectedr   r   r   verifyV  s   


r^   c                 C   s<   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.
    )
r   r1   r2   r   r3   r   rX   r5   r6   rY   )rV   r0   r7   r:   rD   rZ   r   r   r   find_signature_hash|  s
   
r_   infilerC   c                 c   s6    	 |  |}t|}|dkrdS |V  ||k rdS q)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
    Tr   N)readr!   )r`   rC   r;   
read_bytesr   r   r   yield_fixedblocks  s   
rc   r[   c                 C   sz   |t vr
td| t | }| }t| tr||  | S t| dr*t| jds,J t| dD ]}|| q1| S )a>  Returns 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:`rsa.pkcs1.HASH_METHODS`.

    rM   ra   __call__i   )	r	   rO   
isinstancebytesupdatehasattrra   rc   digest)r   r[   methodhasherr;   r   r   r   rS     s   

rS   rZ   c                 C   s*   t  D ]\}}|| v r|  S qtd)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
    rW   )rN   itemsr   )rZ   hashnamerQ   r   r   r   rY     s
   rY   )r<   rJ   rU   r^   r   r   r   __main__z'Running doctests 1000x or until failurei  d   z%i timeszDoctests done)@r   hashlibr#   systypinghmacr    r   r   r   r   TYPE_CHECKING_HashHashTypeAnyrN   md5sha1sha224sha256sha384sha512r	   DictstrCallable__annotations__version_inforg   sha3_256sha3_384sha3_512	Exceptionr   r   r   rf   intr-   r/   	PublicKeyr<   
PrivateKeyrJ   rR   rU   r^   r_   BinaryIOIteratorrc   UnionrS   rY   __all__r   printdoctestrangecounttestmodfailurestestsr   r   r   r   <module>   s   
"
	-! S!&"

