o
    e}n                     @   s   d Z ddlZddlZddlZddlZddlZddlZddlZddl	ZdZ
ejdddZG dd dZG dd	 d	eZG d
d deZejjdfdedejegef dedejeef fddZdedededejeef fddZdededejeef fddZde
fdedejegef dededejeeeef f
ddZdde
fdededededejeef f
ddZg d Zed!krddlZz%ed"D ]Ze  \Z!Z"e!r ned# dkresedkre#d$e  qW n e$y   e#d% Y dS w e#d& dS 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.

    Ni  TAbstractKey)boundc                
   @   s@  e Zd ZdZdZdededdfddZed	ej	e
 d
ede
fddZed	ej	e
 d
ede
fddZdefddZdefddZed(d	ej	e
 d
edede
fddZededejeejf dejfddZd(dedefddZdedejeef fddZd ed!edefd"d#Zdefd$d%Zdejeef fd&d'ZdS ))r   z0Abstract superclass for private and public keys.)neblindfacblindfac_inversemutexr   r   returnNc                 C   s&   || _ || _d | _| _t | _d S )N)r   r   r   r   	threadingLockr	   )selfr   r    r   2/usr/local/lib/python3.10/dist-packages/rsa/key.py__init__8   s   zAbstractKey.__init__clskeyfilec                 C      dS )zLoads a key in PKCS#1 PEM format, implement in a subclass.

        :param keyfile: contents of a PEM-encoded file that contains
            the public key.
        :type keyfile: bytes

        :return: the loaded key
        :rtype: AbstractKey
        Nr   r   r   r   r   r   _load_pkcs1_pemC       zAbstractKey._load_pkcs1_pemc                 C   r   )zLoads a key in PKCS#1 PEM format, implement in a subclass.

        :param keyfile: contents of a DER-encoded file that contains
            the public key.
        :type keyfile: bytes

        :return: the loaded key
        :rtype: AbstractKey
        Nr   r   r   r   r   _load_pkcs1_derO   r   zAbstractKey._load_pkcs1_derc                 C   r   )zSaves the key in PKCS#1 PEM format, implement in a subclass.

        :returns: the PEM-encoded key.
        :rtype: bytes
        Nr   r   r   r   r   _save_pkcs1_pem[   r   zAbstractKey._save_pkcs1_pemc                 C   r   )zSaves the key in PKCS#1 DER format, implement in a subclass.

        :returns: the DER-encoded key.
        :rtype: bytes
        Nr   r   r   r   r   _save_pkcs1_derb   r   zAbstractKey._save_pkcs1_derPEMformatc                 C   s"   | j | jd}| ||}||S )aN  Loads a key in PKCS#1 DER or PEM format.

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

        :return: the loaded key
        :rtype: AbstractKey
        r   DER)r   r   _assert_format_exists)r   r   r   methodsmethodr   r   r   
load_pkcs1i   s
   zAbstractKey.load_pkcs1file_formatr!   c              
   C   sH   z||  W S  t y# } zdt| }td| |f |d}~ww )z9Checks whether the given file format exists in 'methods'.z, z%Unsupported format: %r, try one of %sN)KeyErrorjoinsortedkeys
ValueError)r$   r!   exformatsr   r   r   r       s   

z!AbstractKey._assert_format_existsc                 C   s    | j | jd}| ||}| S )zSaves the key in PKCS#1 DER or PEM format.

        :param format: the format to save; 'PEM' or 'DER'
        :type format: str
        :returns: the DER- or PEM-encoded key.
        :rtype: bytes
        r   )r   r   r    )r   r   r!   r"   r   r   r   
save_pkcs1   s
   
zAbstractKey.save_pkcs1messagec                 C   s.   |   \}}|t|| j| j | j }||fS )a  Performs blinding on the message.

        :param message: the message, as integer, to blind.
        :param r: the random number to blind with.
        :return: tuple (the blinded message, the inverse of the used blinding factor)

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

        See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29
        )_update_blinding_factorpowr   r   )r   r-   r   r   blindedr   r   r   blind   s   zAbstractKey.blindr0   r   c                 C   s   || | j  S )a  Performs blinding on the message using random number 'blindfac_inverse'.

        :param blinded: the blinded message, as integer, to unblind.
        :param blindfac: the factor 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
        )r   )r   r0   r   r   r   r   unblind   s   zAbstractKey.unblindc                 C   s@   t dD ]}tj| jd }tj| j|r|  S qtd)Ni     zunable to find blinding factor)rangersarandnumrandintr   primeare_relatively_primeRuntimeError)r   _blind_rr   r   r   _initial_blinding_factor   s   z$AbstractKey._initial_blinding_factorc                 C   s   | j 5 | jdk r|  | _tj| j| j| _nt| jd| j| _t| jd| j| _| j| jfW  d   S 1 s;w   Y  dS )a  Update blinding factors.

        Computing a blinding factor is expensive, so instead this function
        does this once, then updates the blinding factor as per section 9
        of 'A Timing Attack against RSA with the Chinese Remainder Theorem'
        by Werner Schindler.
        See https://tls.mbed.org/public/WSchindler-RSA_Timing_Attack.pdf

        :return: the new blinding factor and its inverse.
        r      N)	r	   r   r=   r5   commoninverser   r   r/   r   r   r   r   r.      s   


$z#AbstractKey._update_blinding_factor)r   )__name__
__module____qualname____doc__	__slots__intr   classmethodtypingTyper   bytesr   r   r   r   strr#   staticmethodMappingCallabler    r,   Tupler1   r2   r=   r.   r   r   r   r   r   3   s2    $c                   @   s  e Zd ZdZdZdedefddZdefddZde	j
eef fd	d
Zde	j
eef ddfddZde	jdefddZde	jdefddZdefddZededd fddZdefddZededd fddZdefddZededd fdd Zededd f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 access 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   keyr
   c                 C   
   t | |S Ngetattrr   rQ   r   r   r   __getitem__      
zPublicKey.__getitem__c                 C   s   d| j | jf S )NzPublicKey(%i, %i)r   r   r   r   r   r   __repr__      zPublicKey.__repr__c                 C   s   | j | jfS z&Returns the key as tuple for pickling.rY   r   r   r   r   __getstate__   s   zPublicKey.__getstate__stateNc                 C   s"   |\| _ | _t| | j | j dS zSets the key from tuple.N)r   r   r   r   r   r^   r   r   r   __setstate__   s   zPublicKey.__setstate__otherc                 C   s2   |d u rdS t |tsdS | j|jko| j|jkS NF)
isinstancerP   r   r   r   rb   r   r   r   __eq__  s
   
zPublicKey.__eq__c                 C   
   | |k S rS   r   re   r   r   r   __ne__  rX   zPublicKey.__ne__c                 C   s   t | j| jfS rS   )hashr   r   r   r   r   r   __hash__  r[   zPublicKey.__hash__r   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asn1SpecmoduluspublicExponentrY   )pyasn1.codec.derrl   rsa.asn1rn   decoderF   )r   r   rl   rn   privr;   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 )zxSaves the public key in PKCS#1 DER format.

        :returns: the DER-encoded public key.
        :rtype: bytes
        r   encoderrm   rq   rr   )rs   rx   rt   rn   setComponentByNamer   r   encode)r   rx   rn   asn_keyr   r   r   r   -  s   
zPublicKey._save_pkcs1_derc                 C      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r5   pemload_pemr   r   r   derr   r   r   r   >  s   
zPublicKey._load_pkcs1_pemc                 C      |   }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.
        :rtype: bytes
        r}   r   r5   r   save_pemr   r   r   r   r   r   M     zPublicKey._save_pkcs1_pemc                 C   r|   )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.
        :type keyfile: bytes
        :return: a PublicKey object
        z
PUBLIC KEY)r5   r   r   load_pkcs1_openssl_derr   r   r   r   load_pkcs1_openssl_pemW  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r+t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   )OpenSSLPubKeyrk   )univro   headeroidz1.2.840.113549.1.1.1z7This is not a DER-encoded OpenSSL-compatible public keyrQ   r3   N)
rt   r   rs   rl   pyasn1.typer   ru   ObjectIdentifier	TypeErrorr   )r   r   r   rl   r   keyinfor;   r   r   r   r   j  s   	z PublicKey.load_pkcs1_openssl_der)rA   rB   rC   rD   rE   rK   rF   rW   rZ   rH   rO   r]   ra   Anyboolrf   rh   rj   rG   rJ   r   r   r   r   r   r   r   r   r   r   rP      s(    	
rP   c                   @   sD  e Zd ZdZdZdedededededd	fd
dZdedefddZdefddZ	de
jeeeeeeeef fddZde
jeeeeeeeef dd	fddZde
jdefddZde
jdefddZdefddZdedefddZd edefd!d"Zed#edd fd$d%Zdefd&d'Zed#edd fd(d)Zdef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 access is
    faster, though.

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

    exp1, exp2 and coef will be calculated:

    >>> pk = PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
    >>> pk.exp1
    55063
    >>> pk.exp2
    10095
    >>> pk.coef
    50797

    )dpqexp1exp2coefr   r   r   r   r   r
   Nc                 C   sX   t | || || _|| _|| _t||d  | _t||d  | _tj	
||| _d S )Nr3   )r   r   r   r   r   rF   r   r   r5   r?   r@   r   )r   r   r   r   r   r   r   r   r   r     s   zPrivateKey.__init__rQ   c                 C   rR   rS   rT   rV   r   r   r   rW     rX   zPrivateKey.__getitem__c                 C   s   d| j | j| j| j| jf S )NzPrivateKey(%i, %i, %i, %i, %i))r   r   r   r   r   r   r   r   r   rZ     s   zPrivateKey.__repr__c                 C   s$   | j | j| j| j| j| j| j| jfS r\   )r   r   r   r   r   r   r   r   r   r   r   r   r]     s   $zPrivateKey.__getstate__r^   c              	   C   s:   |\| _ | _| _| _| _| _| _| _t	| | j | j dS r_   )
r   r   r   r   r   r   r   r   r   r   r`   r   r   r   ra     s   $zPrivateKey.__setstate__rb   c                 C   sz   |d u rdS t |tsdS | j|jko<| j|jko<| j|jko<| j|jko<| j|jko<| j|jko<| j|jko<| j	|j	kS rc   )
rd   r   r   r   r   r   r   r   r   r   re   r   r   r   rf     s&   







zPrivateKey.__eq__c                 C   rg   rS   r   re   r   r   r   rh     rX   zPrivateKey.__ne__c              	   C   s(   t | j| j| j| j| j| j| j| jfS rS   )	ri   r   r   r   r   r   r   r   r   r   r   r   r   rj     s   (zPrivateKey.__hash__	encryptedc                 C   s\   |  |\}}t|| j| j}t|| j| j}|| | 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
        )r1   r/   r   r   r   r   r   r2   )r   r   r0   r   s1s2h	decryptedr   r   r   blinded_decrypt  s   zPrivateKey.blinded_decryptr-   c                 C   s.   |  |\}}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
        )r1   r5   coreencrypt_intr   r   r2   )r   r-   r0   r   r   r   r   r   blinded_encrypt  s   
zPrivateKey.blinded_encryptr   c           
      C   s   ddl m} ||\}}|d dkrtd|d  tt|dd }| | }tt|dd \}}}	|j|j|jf|||	fkrGt	
dt |S )a4  Loads a key in PKCS#1 DER format.

        :param keyfile: contents of a DER-encoded file that contains the private
            key.
        :type keyfile: bytes
        :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   rk   z)Unable to read this file, version %s != 0r3      	   zYou have provided a malformed keyfile. Either the exponents or the coefficient are incorrect. Using the correct values instead.)rs   rl   ru   r)   maprF   r   r   r   warningswarnUserWarning)
r   r   rl   rv   r;   as_intsrQ   r   r   r   r   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 )zzSaves the private key in PKCS#1 DER format.

        :returns: the DER-encoded private key.
        :rtype: bytes
        r   )r   	namedtyperw   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versionrq   rr   privateExponentprime1prime2	exponent1	exponent2coefficientN)rA   rB   rC   
NamedTypes	NamedTypeIntegercomponentTyper   r   r   r   r   
AsnPrivKey<  s    r   r   rq   rr   r   r   r   r   r   r   )r   r   r   rs   rx   Sequencery   r   r   r   r   r   r   r   r   rz   )r   rx   r   r{   r   r   r   r   2  s   
zPrivateKey._save_pkcs1_derc                 C   r|   )aq  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.
        :type keyfile: bytes
        :return: a PrivateKey object
           RSA PRIVATE KEYr~   r   r   r   r   r   W  s   
zPrivateKey._load_pkcs1_pemc                 C   r   )zSaves a PKCS#1 PEM-encoded private key file.

        :return: contents of a PEM-encoded file that contains the private key.
        :rtype: bytes
        r   r   r   r   r   r   r   g  r   zPrivateKey._save_pkcs1_pem)rA   rB   rC   rD   rE   rF   r   rK   rW   rZ   rH   rO   r]   ra   r   r   rf   rh   rj   r   r   rG   rJ   r   r   r   r   r   r   r   r   r     s&    "$	(:%r   Tnbitsgetprime_funcaccurater
   c           
         s   | d | d }| | }| | }||}||}dt dt dtf fdd}d}	|||s@|	r4||}n||}|	 }	|||r-t||t||fS )	a&  Returns a tuple of two different primes of nbits bits each.

    The resulting p * q has exactly 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

    r>      r   r   r
   c                    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)r5   r?   bit_size)r   r   
found_sizer   
total_bitsr   r   is_acceptable  s   zfind_p_q.<locals>.is_acceptableF)rF   r   maxmin)
r   r   r   shiftpbitsqbitsr   r   r   change_pr   r   r   find_p_qr  s   #


r   r   r   exponentc                 C   s   | d |d  }z	t j||}W n  t jjy1 } zt jj|||jd|||jf d|d}~ww || | dkrCt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

    r3   z;e (%d) and phi_n (%d) are not relatively prime (divider=%i))msgNz6e (%d) and d (%d) are not mult. inv. modulo phi_n (%d))r5   r?   r@   NotRelativePrimeErrorr   r)   )r   r   r   phi_nr   r*   r   r   r   calculate_keys_custom_exponent  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)r   r   r   r   r   calculate_keys  s   
r   c                 C   sN   	 t | d ||\}}zt|||d\}}W n
 ty   Y nw 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
    Tr>   )r   )r   r   r)   )r   r   r   r   r   r   r   r   r   r   r   gen_keys  s   r   r3   poolsizec           
         s   | dk rt ddk rt d dkr)ddlm  dtdtf fd	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 smallr3   zPool size (%i) should be >= 1r   )parallelr   r
   c                    s    j | dS )N)r   )getprime)r   r   r   r   r   r   ;  s   znewkeys.<locals>.getprime_func)r   r   )	r)   r5   r   rF   r8   r   r   rP   r   )
r   r   r   r   r   r   r   r   r   r   r   r   r   newkeys  s   r   )rP   r   r   __main__d   
   z%i timesAbortedzDoctests done)%rD   r   rH   r   	rsa.primer5   rsa.pem
rsa.commonrsa.randnumrsa.corer   TypeVarr   r   rP   r   r8   r   rF   rN   r   rO   r   r   r   r   r   __all__rA   doctestr4   counttestmodfailurestestsprintKeyboardInterruptr   r   r   r   <module>   s    ( & v
$P "
#
8