a
    dbSY                     @   sR  d Z ddlZddlmZ ddlZddlZddlZddlZddl	Ze
eZdZG dd deZG dd deZG d	d
 d
eZejjdfddZdd Zdd ZdefddZddefddZg dZedkrNddlZzPedD ]BZe \ZZer q&ered dksedkre de  qW n e!yD   e d Y n
0 e d dS )aj  RSA key generation code.

Create new keys with the newkeys() function. It will give you a PublicKey and a
PrivateKey object.

Loading and saving keys requires the pyasn1 module. This module is imported as
late as possible, such that other functionality will remain working in absence
of pyasn1.

.. note::

    Storing public and private keys via the `pickle` module is possible.
    However, it is insecure to load a key from an untrusted source.
    The pickle module is not secure against erroneous or maliciously
    constructed data. Never unpickle data received from an untrusted
    or unauthenticated source.

    N)bi  c                   @   sP   e Zd ZdZdZdd ZedddZedd	 Z	dd
dZ
dd Zdd ZdS )AbstractKeyz0Abstract superclass for private and public keys.nec                 C   s   || _ || _d S Nr   )selfr   r    r	   X/home/tom/ab/renpy-build/tmp/install.linux-x86_64/lib/python3.9/site-packages/rsa/key.py__init__6   s    zAbstractKey.__init__PEMc                 C   s"   | j | jd}| ||}||S )a  Loads a key in PKCS#1 DER or PEM format.

        :param keyfile: contents of a DER- or PEM-encoded file that contains
            the public key.
        :param format: the format of the file to load; 'PEM' or 'DER'

        :return: a PublicKey object
        r   ZDER)_load_pkcs1_pem_load_pkcs1_der_assert_format_exists)clskeyfileformatmethodsmethodr	   r	   r
   
load_pkcs1:   s
    zAbstractKey.load_pkcs1c                 C   sD   z
||  W S  t y>   dt| }td| |f Y n0 dS )zBChecks whether the given file format exists in 'methods'.
        z, z%Unsupported format: %r, try one of %sN)KeyErrorjoinsortedkeys
ValueError)Zfile_formatr   formatsr	   r	   r
   r   M   s    
z!AbstractKey._assert_format_existsc                 C   s    | j | jd}| ||}| S )zSaves the public key in PKCS#1 DER or PEM format.

        :param format: the format to save; 'PEM' or 'DER'
        :returns: the DER- or PEM-encoded public key.
        r   )_save_pkcs1_pem_save_pkcs1_derr   )r   r   r   r   r	   r	   r
   
save_pkcs1Y   s
    zAbstractKey.save_pkcs1c                 C   s   |t || j| j | j S )a  Performs blinding on the message using random number 'r'.

        :param message: the message, as integer, to blind.
        :type message: int
        :param r: the random number to blind with.
        :type r: int
        :return: the blinded message.
        :rtype: int

        The blinding is such that message = unblind(decrypt(blind(encrypt(message))).

        See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29
        )powr   r   )r   messagerr	   r	   r
   blindh   s    zAbstractKey.blindc                 C   s   t j|| j| | j S )a  Performs blinding on the message using random number 'r'.

        :param blinded: the blinded message, as integer, to unblind.
        :param r: the random number to unblind with.
        :return: the original message.

        The blinding is such that message = unblind(decrypt(blind(encrypt(message))).

        See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29
        )rsacommoninverser   )r   blindedr"   r	   r	   r
   unblindy   s    zAbstractKey.unblindN)r   )r   )__name__
__module____qualname____doc__	__slots__r   classmethodr   staticmethodr   r   r#   r(   r	   r	   r	   r
   r   1   s   

r   c                   @   s   e Zd ZdZdZdd Zdd Zdd Zd	d
 Zdd Z	dd Z
edd Zdd Zedd Zdd Zedd Zedd ZdS )	PublicKeya  Represents a public RSA key.

    This key is also known as the 'encryption key'. It contains the 'n' and 'e'
    values.

    Supports attributes as well as dictionary-like access. Attribute accesss is
    faster, though.

    >>> PublicKey(5, 3)
    PublicKey(5, 3)

    >>> key = PublicKey(5, 3)
    >>> key.n
    5
    >>> key['n']
    5
    >>> key.e
    3
    >>> key['e']
    3

    r   c                 C   s
   t | |S r   getattrr   keyr	   r	   r
   __getitem__   s    zPublicKey.__getitem__c                 C   s   d| j | jf S )NzPublicKey(%i, %i)r   r   r	   r	   r
   __repr__   s    zPublicKey.__repr__c                 C   s   | j | jfS z&Returns the key as tuple for pickling.r   r6   r	   r	   r
   __getstate__   s    zPublicKey.__getstate__c                 C   s   |\| _ | _dS zSets the key from tuple.Nr   r   stater	   r	   r
   __setstate__   s    zPublicKey.__setstate__c                 C   s2   |d u rdS t |tsdS | j|jko0| j|jkS NF)
isinstancer0   r   r   r   otherr	   r	   r
   __eq__   s
    
zPublicKey.__eq__c                 C   s
   | |k S r   r	   r@   r	   r	   r
   __ne__   s    zPublicKey.__ne__c                 C   sH   ddl m} ddlm} |j|| d\}}| t|d t|d dS )a  Loads a key in PKCS#1 DER format.

        :param keyfile: contents of a DER-encoded file that contains the public
            key.
        :return: a PublicKey object

        First let's construct a DER encoded key:

        >>> import base64
        >>> b64der = 'MAwCBQCNGmYtAgMBAAE='
        >>> der = base64.standard_b64decode(b64der)

        This loads the file:

        >>> PublicKey._load_pkcs1_der(der)
        PublicKey(2367317549, 65537)

        r   decoder	AsnPubKeyZasn1SpecmoduluspublicExponentr   )pyasn1.codec.derrE   rsa.asn1rG   decodeint)r   r   rE   rG   priv_r	   r	   r
   r      s    zPublicKey._load_pkcs1_derc                 C   sD   ddl m} ddlm} | }|d| j |d| j ||S )zbSaves the public key in PKCS#1 DER format.

        @returns: the DER-encoded public key.
        r   encoderrF   rI   rJ   )rK   rR   rL   rG   setComponentByNamer   r   encode)r   rR   rG   asn_keyr	   r	   r
   r      s    zPublicKey._save_pkcs1_derc                 C   s   t j|d}| |S )aO  Loads a PKCS#1 PEM-encoded public key file.

        The contents of the file before the "-----BEGIN RSA PUBLIC KEY-----" and
        after the "-----END RSA PUBLIC KEY-----" lines is ignored.

        :param keyfile: contents of a PEM-encoded file that contains the public
            key.
        :return: a PublicKey object
        RSA PUBLIC KEY)r$   pemload_pemr   r   r   derr	   r	   r
   r      s    zPublicKey._load_pkcs1_pemc                 C   s   |   }tj|dS )zSaves a PKCS#1 PEM-encoded public key file.

        :return: contents of a PEM-encoded file that contains the public key.
        rV   )r   r$   rW   save_pemr   rZ   r	   r	   r
   r      s    zPublicKey._save_pkcs1_pemc                 C   s   t j|d}| |S )a  Loads a PKCS#1.5 PEM-encoded public key file from OpenSSL.

        These files can be recognised in that they start with BEGIN PUBLIC KEY
        rather than BEGIN RSA PUBLIC KEY.

        The contents of the file before the "-----BEGIN PUBLIC KEY-----" and
        after the "-----END PUBLIC KEY-----" lines is ignored.

        :param keyfile: contents of a PEM-encoded file that contains the public
            key, from OpenSSL.
        :return: a PublicKey object
        z
PUBLIC KEY)r$   rW   rX   load_pkcs1_openssl_derrY   r	   r	   r
   load_pkcs1_openssl_pem   s    z PublicKey.load_pkcs1_openssl_pemc                 C   sl   ddl m} ddlm} ddlm} |j|| d\}}|d d |dkrVtd	| 	|d
 dd S )zLoads a PKCS#1 DER-encoded public key file from OpenSSL.

        :param keyfile: contents of a DER-encoded file that contains the public
            key, from OpenSSL.
        :return: a PublicKey object

        r   )OpenSSLPubKeyrD   )univrH   headeroidz1.2.840.113549.1.1.1z7This is not a DER-encoded OpenSSL-compatible public keyr4      N)
rL   r_   rK   rE   pyasn1.typer`   rM   ZObjectIdentifier	TypeErrorr   )r   r   r_   rE   r`   ZkeyinforP   r	   r	   r
   r]     s    
z PublicKey.load_pkcs1_openssl_derN)r)   r*   r+   r,   r-   r5   r7   r9   r=   rB   rC   r.   r   r   r   r   r^   r]   r	   r	   r	   r
   r0      s$   	

	
r0   c                   @   s   e Zd ZdZdZdddZdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zedd Zdd Zedd Zdd ZdS )
PrivateKeya;  Represents a private RSA key.

    This key is also known as the 'decryption key'. It contains the 'n', 'e',
    'd', 'p', 'q' and other values.

    Supports attributes as well as dictionary-like access. Attribute accesss is
    faster, though.

    >>> PrivateKey(3247, 65537, 833, 191, 17)
    PrivateKey(3247, 65537, 833, 191, 17)

    exp1, exp2 and coef can be given, but if None or omitted they will be calculated:

    >>> pk = PrivateKey(3727264081, 65537, 3349121513, 65063, 57287, exp2=4)
    >>> pk.exp1
    55063
    >>> pk.exp2  # this is of course not a correct value, but it is the one we passed.
    4
    >>> pk.coef
    50797

    If you give exp1, exp2 or coef, they will be used as-is:

    >>> pk = PrivateKey(1, 2, 3, 4, 5, 6, 7, 8)
    >>> pk.exp1
    6
    >>> pk.exp2
    7
    >>> pk.coef
    8

    r   r   dpqexp1exp2coefNc	           	      C   s   t | || || _|| _|| _|d u r<t||d  | _n|| _|d u r^t||d  | _n|| _|d u r~tj	
||| _n|| _d S )Nrc   )r   r   rh   ri   rj   rN   rk   rl   r$   r%   r&   rm   )	r   r   r   rh   ri   rj   rk   rl   rm   r	   r	   r
   r   K  s    zPrivateKey.__init__c                 C   s
   t | |S r   r1   r3   r	   r	   r
   r5   a  s    zPrivateKey.__getitem__c                 C   s   d|  S )Nz-PrivateKey(%(n)i, %(e)i, %(d)i, %(p)i, %(q)i)r	   r6   r	   r	   r
   r7   d  s    zPrivateKey.__repr__c                 C   s$   | j | j| j| j| j| j| j| jfS r8   rg   r6   r	   r	   r
   r9   g  s    zPrivateKey.__getstate__c              	   C   s(   |\| _ | _| _| _| _| _| _| _dS r:   rg   r;   r	   r	   r
   r=   k  s    zPrivateKey.__setstate__c                 C   sz   |d u rdS t |tsdS | j|jkox| j|jkox| j|jkox| j|jkox| j|jkox| j|jkox| j|jkox| j	|j	kS r>   )
r?   rf   r   r   rh   ri   rj   rk   rl   rm   r@   r	   r	   r
   rB   o  s&    







zPrivateKey.__eq__c                 C   s
   | |k S r   r	   r@   r	   r	   r
   rC     s    zPrivateKey.__ne__c                 C   s>   t j| jd }| ||}t j|| j| j}| ||S )zDecrypts the message using blinding to prevent side-channel attacks.

        :param encrypted: the encrypted message
        :type encrypted: int

        :returns: the decrypted message
        :rtype: int
        rc   )	r$   randnumrandintr   r#   coreZdecrypt_intrh   r(   )r   	encryptedblind_rr'   Z	decryptedr	   r	   r
   blinded_decrypt  s    
zPrivateKey.blinded_decryptc                 C   s>   t j| jd }| ||}t j|| j| j}| ||S )zEncrypts the message using blinding to prevent side-channel attacks.

        :param message: the message to encrypt
        :type message: int

        :returns: the encrypted message
        :rtype: int
        rc   )	r$   rn   ro   r   r#   rp   Zencrypt_intrh   r(   )r   r!   rr   r'   rq   r	   r	   r
   blinded_encrypt  s    
zPrivateKey.blinded_encryptc                 C   sX   ddl m} ||\}}|d dkr6td|d  tdd |dd D }| | S )a  Loads a key in PKCS#1 DER format.

        :param keyfile: contents of a DER-encoded file that contains the private
            key.
        :return: a PrivateKey object

        First let's construct a DER encoded key:

        >>> import base64
        >>> b64der = 'MC4CAQACBQDeKYlRAgMBAAECBQDHn4npAgMA/icCAwDfxwIDANcXAgInbwIDAMZt'
        >>> der = base64.standard_b64decode(b64der)

        This loads the file:

        >>> PrivateKey._load_pkcs1_der(der)
        PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)

        r   rD   z)Unable to read this file, version %s != 0c                 s   s   | ]}t |V  qd S r   )rN   ).0xr	   r	   r
   	<genexpr>      z-PrivateKey._load_pkcs1_der.<locals>.<genexpr>rc   	   )rK   rE   rM   r   tuple)r   r   rE   rO   rP   Zas_intsr	   r	   r
   r     s    zPrivateKey._load_pkcs1_derc                    s   ddl mm  ddlm} G  fdddj}| }|dd |d| j |d| j |d	| j	 |d
| j
 |d| j |d| j |d| j |d| j ||S )zdSaves the private key in PKCS#1 DER format.

        @returns: the DER-encoded private key.
        r   )r`   	namedtyperQ   c                       s   e Zd Z  d  d  d  d  d  d  d  d  d	 	Zd
S )z.PrivateKey._save_pkcs1_der.<locals>.AsnPrivKeyversionrI   rJ   privateExponentprime1prime2	exponent1	exponent2coefficientN)r)   r*   r+   Z
NamedTypesZ	NamedTypeZIntegerZcomponentTyper	   r{   r`   r	   r
   
AsnPrivKey  s   r   r|   rI   rJ   r}   r~   r   r   r   r   )rd   r`   r{   rK   rR   SequencerS   r   r   rh   ri   rj   rk   rl   rm   rT   )r   rR   r   rU   r	   r   r
   r     s    zPrivateKey._save_pkcs1_derc                 C   s   t j|td}| |S )aT  Loads a PKCS#1 PEM-encoded private key file.

        The contents of the file before the "-----BEGIN RSA PRIVATE KEY-----" and
        after the "-----END RSA PRIVATE KEY-----" lines is ignored.

        :param keyfile: contents of a PEM-encoded file that contains the private
            key.
        :return: a PrivateKey object
        RSA PRIVATE KEY)r$   rW   rX   r   r   rY   r	   r	   r
   r     s    zPrivateKey._load_pkcs1_pemc                 C   s   |   }tj|tdS )zSaves a PKCS#1 PEM-encoded private key file.

        :return: contents of a PEM-encoded file that contains the private key.
        r   )r   r$   rW   r[   r   r\   r	   r	   r
   r     s    zPrivateKey._save_pkcs1_pem)NNN)r)   r*   r+   r,   r-   r   r5   r7   r9   r=   rB   rC   rs   rt   r.   r   r   r   r   r	   r	   r	   r
   rf   '  s"   !

,$
rf   Tc           
         s   | d | d }| | }| | }t d|  ||}t d|  ||} fdd}d}	|||s|	rr||}n||}|	 }	qZt||t||fS )a%  Returns a tuple of two different primes of nbits bits each.

    The resulting p * q has exacty 2 * nbits bits, and the returned p and q
    will not be equal.

    :param nbits: the number of bits in each of p and q.
    :param getprime_func: the getprime function, defaults to
        :py:func:`rsa.prime.getprime`.

        *Introduced in Python-RSA 3.1*

    :param accurate: whether to enable accurate mode or not.
    :returns: (p, q), where p > q

    >>> (p, q) = find_p_q(128)
    >>> from rsa import common
    >>> common.bit_size(p * q)
    256

    When not in accurate mode, the number of bits can be slightly less

    >>> (p, q) = find_p_q(128, accurate=False)
    >>> from rsa import common
    >>> common.bit_size(p * q) <= 256
    True
    >>> common.bit_size(p * q) > 240
    True

          zfind_p_q(%i): Finding pzfind_p_q(%i): Finding qc                    s,   | |krdS  sdS t j| | }|kS )zReturns True iff p and q are acceptable:

            - p and q differ
            - (p * q) has the right nr of bits (when accurate=True)
        FT)r$   r%   Zbit_size)ri   rj   Z
found_sizeaccurateZ
total_bitsr	   r
   is_acceptable8  s    zfind_p_q.<locals>.is_acceptableF)logdebugmaxmin)
nbitsgetprime_funcr   shiftZpbitsZqbitsri   rj   r   Zchange_pr	   r   r
   find_p_q  s     

r   c                 C   sp   | d |d  }zt j||}W n" tyD   td||f Y n0 || | dkrhtd|||f ||fS )a  Calculates an encryption and a decryption key given p, q and an exponent,
    and returns them as a tuple (e, d)

    :param p: the first large prime
    :param q: the second large prime
    :param exponent: the exponent for the key; only change this if you know
        what you're doing, as the exponent influences how difficult your
        private key can be cracked. A very common choice for e is 65537.
    :type exponent: int

    rc   z.e (%d) and phi_n (%d) are not relatively primez6e (%d) and d (%d) are not mult. inv. modulo phi_n (%d))r$   r%   r&   r   )ri   rj   exponentZphi_nrh   r	   r	   r
   calculate_keys_custom_exponentY  s    r   c                 C   s   t | |tS )zCalculates an encryption and a decryption key given p and q, and
    returns them as a tuple (e, d)

    :param p: the first large prime
    :param q: the second large prime

    :return: tuple (e, d) with the encryption and decryption exponents.
    )r   DEFAULT_EXPONENT)ri   rj   r	   r	   r
   calculate_keysu  s    
r   c                 C   sP   t | d ||\}}zt|||d\}}W qDW q  ty@   Y q 0 q ||||fS )aW  Generate RSA keys of nbits bits. Returns (p, q, e, d).

    Note: this can take a long time, depending on the key size.

    :param nbits: the total number of bits in ``p`` and ``q``. Both ``p`` and
        ``q`` will use ``nbits/2`` bits.
    :param getprime_func: either :py:func:`rsa.prime.getprime` or a function
        with similar signature.
    :param exponent: the exponent for the key; only change this if you know
        what you're doing, as the exponent influences how difficult your
        private key can be cracked. A very common choice for e is 65537.
    :type exponent: int
    r   )r   )r   r   r   )r   r   r   r   ri   rj   r   rh   r	   r	   r
   gen_keys  s    r   rc   c                 C   s   | dk rt d|dk r$t d| |dkrRddlm} ddl}|j|j|d}ntjj}t| |||d	\}}}	}
|| }t||	t	||	|
||fS )
a  Generates public and private keys, and returns them as (pub, priv).

    The public key is also known as the 'encryption key', and is a
    :py:class:`rsa.PublicKey` object. The private key is also known as the
    'decryption key' and is a :py:class:`rsa.PrivateKey` object.

    :param nbits: the number of bits required to store ``n = p*q``.
    :param accurate: when True, ``n`` will have exactly the number of bits you
        asked for. However, this makes key generation much slower. When False,
        `n`` may have slightly less bits.
    :param poolsize: the number of processes to use to generate the prime
        numbers. If set to a number > 1, a parallel algorithm will be used.
        This requires Python 2.6 or newer.
    :param exponent: the exponent for the key; only change this if you know
        what you're doing, as the exponent influences how difficult your
        private key can be cracked. A very common choice for e is 65537.
    :type exponent: int

    :returns: a tuple (:py:class:`rsa.PublicKey`, :py:class:`rsa.PrivateKey`)

    The ``poolsize`` parameter was added in *Python-RSA 3.1* and requires
    Python 2.6 or newer.

    r   zKey too smallrc   zPool size (%i) should be >= 1r   )parallelN)poolsize)r   r   )
r   r$   r   	functoolspartialgetprimeprimer   r0   rf   )r   r   r   r   r   r   r   ri   rj   r   rh   r   r	   r	   r
   newkeys  s    r   )r0   rf   r   __main__d   
   z%i timesZAbortedzDoctests done)"r,   loggingZrsa._compatr   Z	rsa.primer$   Zrsa.pemZ
rsa.commonZrsa.randnumZrsa.core	getLoggerr)   r   r   objectr   r0   rf   r   r   r   r   r   r   r   __all__doctestrangecounttestmodZfailurestestsprintKeyboardInterruptr	   r	   r	   r
   <module>   s@   
W   eN5
