o
    5huy                     @   s   g d Z ddlZddlZddlmZ ddlmZmZmZ ddl	m
Z
mZ ddlmZ ddlmZ ddlmZmZmZ dd	lmZmZmZ G d
d deZd#d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 d!Z#e#Z$d"Z%dS )&)generate	construct
import_keyRsaKeyoid    N)Random)tobytesbordtostr)DerSequenceDerNull)bytes_to_long)Integer)test_probable_primegenerate_probable_prime	COMPOSITE)_expand_subject_public_key_info_create_subject_public_key_info _extract_subject_public_key_infoc                   @   sV  e Zd ZdZdd Zedd Zedd Zedd	 Zed
d Z	edd Z
edd Zedd Zedd Zedd Ze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d(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd2d3 Z	6	5dKd7d8Zd9d: Zd;d< Z d=d> Z!d?d@ Z"dAdB Z#dCdD Z$dEdF Z%dGdH Z&dIdJ Z'd5S )Lr   a  Class defining an RSA key, private or public.
    Do not instantiate directly.
    Use :func:`generate`, :func:`construct` or :func:`import_key` instead.

    :ivar n: RSA modulus
    :vartype n: integer

    :ivar e: RSA public exponent
    :vartype e: integer

    :ivar d: RSA private exponent
    :vartype d: integer

    :ivar p: First factor of the RSA modulus
    :vartype p: integer

    :ivar q: Second factor of the RSA modulus
    :vartype q: integer

    :ivar invp: Chinese remainder component (:math:`p^{-1} \text{mod } q`)
    :vartype invp: integer

    :ivar invq: Chinese remainder component (:math:`q^{-1} \text{mod } p`)
    :vartype invq: integer

    :ivar u: Same as ``invp``
    :vartype u: integer
    c                 K   s   t | }t d}|t dB }|||fvrtd| D ]\}}t| d| | q||krF| j| jd  | _| j| jd  | _	d| _
dS dS )a.  Build an RSA key.

        :Keywords:
          n : integer
            The modulus.
          e : integer
            The public exponent.
          d : integer
            The private exponent. Only required for private keys.
          p : integer
            The first factor of the modulus. Only required for private keys.
          q : integer
            The second factor of the modulus. Only required for private keys.
          u : integer
            The CRT coefficient (inverse of p modulo q). Only required for
            private keys.
        ne)pqduzSome RSA components are missing_   N)setkeys
ValueErroritemssetattr_d_p_dp_q_dq_invq)selfkwargs	input_set
public_setprivate_set	componentvalue r0   h/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/Crypto/PublicKey/RSA.py__init__R   s   
zRsaKey.__init__c                 C   
   t | jS N)int_nr)   r0   r0   r1   r   q      
zRsaKey.nc                 C   r3   r4   )r5   _er7   r0   r0   r1   r   u   r8   zRsaKey.ec                 C      |   stdt| jS )Nz-No private exponent available for public keys)has_privateAttributeErrorr5   r#   r7   r0   r0   r1   r   y      
zRsaKey.dc                 C   r:   )Nz.No CRT component 'p' available for public keys)r;   r<   r5   r$   r7   r0   r0   r1   r      r=   zRsaKey.pc                 C   r:   )Nz.No CRT component 'q' available for public keys)r;   r<   r5   r&   r7   r0   r0   r1   r      r=   zRsaKey.qc                 C   r:   )Nz/No CRT component 'dp' available for public keys)r;   r<   r5   r%   r7   r0   r0   r1   dp   r=   z	RsaKey.dpc                 C   r:   )Nz/No CRT component 'dq' available for public keys)r;   r<   r5   r'   r7   r0   r0   r1   dq   r=   z	RsaKey.dqc                 C   s4   |   std| jd u r| j| j| _t| jS )Nz1No CRT component 'invq' available for public keys)r;   r<   r(   r&   inverser$   r5   r7   r0   r0   r1   invq   s
   

zRsaKey.invqc                 C   s   | j S r4   )r   r7   r0   r0   r1   invp   s   zRsaKey.invpc                 C   r:   )Nz.No CRT component 'u' available for public keys)r;   r<   r5   _ur7   r0   r0   r1   r      r=   zRsaKey.uc                 C   s
   | j  S )zSize of the RSA modulus in bitsr6   size_in_bitsr7   r0   r0   r1   rE      r8   zRsaKey.size_in_bitsc                 C   s   | j  d d d S )z9The minimal amount of bytes that can hold the RSA modulusr      rD   r7   r0   r0   r1   size_in_bytes   s   zRsaKey.size_in_bytesc                 C   s>   d|  kr| j k std tdttt|| j| j S )Nr   zPlaintext too large)r6   r    r5   powr   r9   )r)   	plaintextr0   r0   r1   _encrypt   s
   zRsaKey._encryptc           	      C   s   d|  kr| j k std td|  stdtjd| j d}t|t|| j| j  | j  }t|| j| j	}t|| j
| j}|| | j | j }|| j	 | }t|| j || j }|S )Nr   zCiphertext too largezThis is not a private keyr   )min_inclusivemax_exclusive)r6   r    r;   	TypeErrorr   random_rangerH   r9   r%   r$   r'   r&   rC   _mult_modulo_bytesr@   )	r)   
ciphertextrcpm1m2hmpresultr0   r0   r1   _decrypt_to_bytes   s$   
zRsaKey._decrypt_to_bytesc                 C   s   t | |S )zLegacy private method)r   rX   r)   rP   r0   r0   r1   _decrypt   s   zRsaKey._decryptc                 C   s
   t | dS )z"Whether this is an RSA private keyr#   )hasattrr7   r0   r0   r1   r;      s   
zRsaKey.has_privatec                 C      dS NTr0   r7   r0   r0   r1   can_encrypt      zRsaKey.can_encryptc                 C   r\   r]   r0   r7   r0   r0   r1   can_sign   r_   zRsaKey.can_signc                 C   s   t | j| jdS )z^A matching RSA public key.

        Returns:
            a new :class:`RsaKey` object
        r   )r   r6   r9   r7   r0   r0   r1   
public_key   s   zRsaKey.public_keyc                 C   sH   |   |  kr
dS | j|jks| j|jkrdS |   sdS | j|jkS )NFT)r;   r   r   r   r)   otherr0   r0   r1   __eq__   s   zRsaKey.__eq__c                 C   s
   | |k S r4   r0   rb   r0   r0   r1   __ne__   s   
zRsaKey.__ne__c                 C   s   ddl m} |)Nr   )PicklingError)picklerf   )r)   rf   r0   r0   r1   __getstate__   s   zRsaKey.__getstate__c                 C   sP   |   rdt| jt| jt| jt| jf }nd}dt| jt| j|f S )Nz, d=%d, p=%d, q=%d, u=%d zRsaKey(n=%d, e=%d%s))r;   r5   r#   r$   r&   rC   r6   r9   )r)   extrar0   r0   r1   __repr__   s   zRsaKey.__repr__c                 C   s"   |   rd}nd}d|t| f S )NPrivatePublicz%s RSA key at 0x%X)r;   id)r)   key_typer0   r0   r1   __str__   s   zRsaKey.__str__PEMNr   c                 C   s  |durt |}|du rtj}|dkrRdd | j| jfD \}}t|d d@ r,d| }t|d d@ r8d| }d||g}	d	d
d |	D }
dt|
dd  S | 	 rt
d| j| j| j| j| j| j| jd  | j| jd  t| j| jg	 }|dkrd}|dkr|rtdnEddlm} |dkr|du rd}|j|tdt d}n*d}|s|rtdd}|j|t|||t d}d}nd}ttt
| j| jgt }|dkr|S |dkrddlm} |||||}t |S td| )a  Export this RSA key.

        Keyword Args:
          format (string):
            The desired output format:

            - ``'PEM'``. (default) Text output, according to `RFC1421`_/`RFC1423`_.
            - ``'DER'``. Binary output.
            - ``'OpenSSH'``. Text output, according to the OpenSSH specification.
              Only suitable for public keys (not private keys).

            Note that PEM contains a DER structure.

          passphrase (bytes or string):
            (*Private keys only*) The passphrase to protect the
            private key.

          pkcs (integer):
            (*Private keys only*) The standard to use for
            serializing the key: PKCS#1 or PKCS#8.

            With ``pkcs=1`` (*default*), the private key is encoded with a
            simple `PKCS#1`_ structure (``RSAPrivateKey``). The key cannot be
            securely encrypted.

            With ``pkcs=8``, the private key is encoded with a `PKCS#8`_ structure
            (``PrivateKeyInfo``). PKCS#8 offers the best ways to securely
            encrypt the key.

            .. note::
                This parameter is ignored for a public key.
                For DER and PEM, the output is always an
                ASN.1 DER ``SubjectPublicKeyInfo`` structure.

          protection (string):
            (*For private keys only*)
            The encryption scheme to use for protecting the private key
            using the passphrase.

            You can only specify a value if ``pkcs=8``.
            For all possible protection schemes,
            refer to :ref:`the encryption parameters of PKCS#8<enc_params>`.
            The recommended value is
            ``'PBKDF2WithHMAC-SHA512AndAES256-CBC'``.

            If ``None`` (default), the behavior depends on :attr:`format`:

            - if ``format='PEM'``, the obsolete PEM encryption scheme is used.
              It is based on MD5 for key derivation, and 3DES for encryption.

            - if ``format='DER'``, the ``'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'``
              scheme is used.

          prot_params (dict):
            (*For private keys only*)

            The parameters to use to derive the encryption key
            from the passphrase. ``'protection'`` must be also specified.
            For all possible values,
            refer to :ref:`the encryption parameters of PKCS#8<enc_params>`.
            The recommendation is to use ``{'iteration_count':21000}`` for PBKDF2,
            and ``{'iteration_count':131072}`` for scrypt.

          randfunc (callable):
            A function that provides random bytes. Only used for PEM encoding.
            The default is :func:`Crypto.Random.get_random_bytes`.

        Returns:
          bytes: the encoded key

        Raises:
          ValueError:when the format is unknown or when you try to encrypt a private
            key with *DER* format and PKCS#1.

        .. warning::
            If you don't provide a pass phrase, the private key will be
            exported in the clear!

        .. _RFC1421:    http://www.ietf.org/rfc/rfc1421.txt
        .. _RFC1423:    http://www.ietf.org/rfc/rfc1423.txt
        .. _`PKCS#1`:   http://www.ietf.org/rfc/rfc3447.txt
        .. _`PKCS#8`:   http://www.ietf.org/rfc/rfc5208.txt
        NOpenSSHc                 S   s   g | ]}|  qS r0   )to_bytes.0xr0   r0   r1   
<listcomp>d  s    z%RsaKey.export_key.<locals>.<listcomp>r          s   ssh-rsa    c                 S   s    g | ]}t d t|| qS )>I)structpacklen)ru   kpr0   r0   r1   rw   j  s        ssh-rsa r   zRSA PRIVATE KEYDERz&PKCS#1 private key cannot be encryptedPKCS8rq   zPRIVATE KEY)
key_paramszENCRYPTED PRIVATE KEYz"'protection' parameter must be setz"PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC)prot_paramsr   z
PUBLIC KEYrq   z3Unknown key format '%s'. Cannot export the RSA key.)r   r   get_random_bytesr9   r6   r	   joinbinascii
b2a_base64r;   r   r   r   r   r   r   r   r@   encoder    	Crypto.IOr   wrapr   r   r   rq   )r)   format
passphrasepkcs
protectionrandfuncr   e_bytesn_byteskeyparts	keystring
binary_keyro   r   rq   pem_strr0   r0   r1   
export_key  s|   V
	

zRsaKey.export_keyc                 O   s   | j |i |S :meta private:)r   )r)   argsr*   r0   r0   r1   	exportKey  s   zRsaKey.exportKeyc                 C   s   |   S r   )ra   r7   r0   r0   r1   	publickey     zRsaKey.publickeyc                 C      t dr   z,Use module Crypto.Signature.pkcs1_15 insteadNotImplementedError)r)   MKr0   r0   r1   sign  r   zRsaKey.signc                 C   r   r   r   )r)   r   	signaturer0   r0   r1   verify  r   zRsaKey.verifyc                 C   r   r   z+Use module Crypto.Cipher.PKCS1_OAEP insteadr   )r)   rI   r   r0   r0   r1   encrypt  r   zRsaKey.encryptc                 C   r   r   r   rY   r0   r0   r1   decrypt  r   zRsaKey.decryptc                 C      t r   r   r)   r   Br0   r0   r1   blind     zRsaKey.blindc                 C   r   r   r   r   r0   r0   r1   unblind  r   zRsaKey.unblindc                 C   r   r   r   r7   r0   r0   r1   size  r   zRsaKey.size)rq   Nr   NNN)(__name__
__module____qualname____doc__r2   propertyr   r   r   r   r   r>   r?   rA   rB   r   rE   rG   rJ   rX   rZ   r;   r^   r`   ra   rd   re   rh   rk   rp   r   r   r   r   r   r   r   r   r   r   r0   r0   r0   r1   r   4   sd    









	
 r     c                    sv  | dk rt d d dks dk rt d|du rtj}td }}t  | | kr|d| d > k r| d }| | }tdd| d >   ||kr[tdd| d >   fd	d
}t|||dtd| d d >  fdd}t|||d}	|	 }d |	d }
 |
}| | kr|d| d > k s5|	kr|	}	|	}t	| ||	|dS )aB  Create a new RSA key pair.

    The algorithm closely follows NIST `FIPS 186-4`_ in its
    sections B.3.1 and B.3.3. The modulus is the product of
    two non-strong probable primes.
    Each prime passes a suitable number of Miller-Rabin tests
    with random bases and a single Lucas test.

    Args:
      bits (integer):
        Key length, or size (in bits) of the RSA modulus.
        It must be at least 1024, but **2048 is recommended.**
        The FIPS standard only defines 1024, 2048 and 3072.
    Keyword Args:
      randfunc (callable):
        Function that returns random bytes.
        The default is :func:`Crypto.Random.get_random_bytes`.
      e (integer):
        Public RSA exponent. It must be an odd positive integer.
        It is typically a small number with very few ones in its
        binary representation.
        The FIPS standard requires the public exponent to be
        at least 65537 (the default).

    Returns: an RSA key object (:class:`RsaKey`, with private key).

    .. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
    i   z"RSA modulus length must be >= 1024   r      zBRSA public exponent must be a positive, odd integer larger than 2.Nr   c                    s   | ko| d   dkS Nr   )gcd	candidate)r   min_pr0   r1   filter_p  s   zgenerate.<locals>.filter_p)
exact_bitsr   prime_filterd   c                    s*   | ko| d   dkot|  kS r   )r   absr   )r   min_distancemin_qr   r0   r1   filter_q  s
   zgenerate.<locals>.filter_qr   r   r   r   r   r   )
r    r   r   r   rE   sqrtr   lcmr@   r   )bitsr   r   r   r   size_qsize_pr   r   r   r   r   r0   )r   r   r   r   r   r1   r     sB   
!

r   Tc                 C   s  G dd dt }| }td| D ]\}}t||t| q|j}|j}t|ds/t||d}n|j}	t|dr>|j	}
|j
}nt|	| d }|}|d d	krV|d }|d d	ksLd
}td}|s|dk rt|}||k rt|||}|dkr||d krt|d|dkrt||d }
d}n|d9 }||k sj|d7 }|s|dk sb|std||
 d	ksJ ||
 }t|dr|j}n|
|}t|||	|
||d}|rq|dks||krtdt||dkrtd|d@ std| rq|	dks|	|krtdt||	dkrtd|
| |krtdt|
tkr#tdt|tkr.td|
d |d  }||
d |d  }||	 t| dkrPtdt|drq|dks`||krdtd|
| | dkrqtd|S )a3  Construct an RSA key from a tuple of valid RSA components.

    The modulus **n** must be the product of two primes.
    The public exponent **e** must be odd and larger than 1.

    In case of a private key, the following equations must apply:

    .. math::

        \begin{align}
        p*q &= n \\
        e*d &\equiv 1 ( \text{mod lcm} [(p-1)(q-1)]) \\
        p*u &\equiv 1 ( \text{mod } q)
        \end{align}

    Args:
        rsa_components (tuple):
            A tuple of integers, with at least 2 and no
            more than 6 items. The items come in the following order:

            1. RSA modulus *n*.
            2. Public exponent *e*.
            3. Private exponent *d*.
               Only required if the key is private.
            4. First factor of *n* (*p*).
               Optional, but the other factor *q* must also be present.
            5. Second factor of *n* (*q*). Optional.
            6. CRT coefficient *q*, that is :math:`p^{-1} \text{mod }q`. Optional.

    Keyword Args:
        consistency_check (boolean):
            If ``True``, the library will verify that the provided components
            fulfil the main RSA properties.

    Raises:
        ValueError: when the key being imported fails the most basic RSA validity checks.

    Returns: An RSA key object (:class:`RsaKey`).
    c                   @   s   e Zd ZdS )zconstruct.<locals>.InputCompsN)r   r   r   r0   r0   r0   r1   
InputCompsD  s    r   r   r   r   r   r   r   r   Fr   Tz2Unable to compute factors p and q from exponent d.r   zInvalid RSA public exponentz-RSA public exponent is not coprime to moduluszRSA modulus is not oddzInvalid RSA private exponentz.RSA private exponent is not coprime to modulusz RSA factors do not match moduluszRSA factor p is compositezRSA factor q is compositezInvalid RSA conditionzInvalid RSA component uzInvalid RSA component u with p)objectzipr"   r   r   r   r[   r   r   r   r   rH   r   r    r   r@   r;   r   r   r5   )rsa_componentsconsistency_checkr   input_compscompr/   r   r   keyr   r   r   ktottspottedakcandr   phir   r0   r0   r1   r     s   )

$


r   c                 G   sN   t  j| ddd}|d dkrtdt|dd t|d |d	 g S )
N	   Tnr_elementsonly_ints_expectedr   z(No PKCS#1 encoding of an RSA private keyr            )r   decoder    r   r   r@   encodedr*   derr0   r0   r1   _import_pkcs1_private  s   (r   c                 G   s   t  j| ddd}t|S )Nr   Tr   )r   r   r   r   r0   r0   r1   _import_pkcs1_public  s   r   c                 G   s6   t df}t| \}}}||vs|d urtdt|S )N1.2.840.113549.1.1.10zNo RSA subjectPublicKeyInfo)r   r   r    r   )r   r*   oidsalgoidencoded_keyparamsr0   r0   r1   _import_subjectPublicKeyInfo  s
   r   c                 G   s   t | }t|S r4   )r   r   )r   r*   sp_infor0   r0   r1   _import_x509_cert  s   r   c                 C   sB   ddl m} tdf}|| |}|d |vrtdt|d |S )Nr   r   r   zNo PKCS#8 encoded RSA keyr   )r   r   r   unwrapr    _import_keyDER)r   r   r   r   r   r0   r0   r1   _import_pkcs8  s   r   c              	   C   sB   t ttttf}|D ]}z|| |W   S  ty   Y q	w td)z@Import an RSA key (public or private half), encoded in DER form.RSA key format is not supported)r   r   r   r   r   r    )
extern_keyr   	decodingsdecodingr0   r0   r1   r     s   r   c                 C   s   ddl m}m}m}m} || |\}}|dkrtd||\}}||\}	}||\}
}||\}}||\}}||\}}||\}}|| dd ||	|
|||fD }t|S )Nr   )import_openssh_private_generic
read_bytesread_stringcheck_paddingzssh-rsazThis SSH key is not RSAc                 S   s   g | ]}t |qS r0   )r   
from_bytesrt   r0   r0   r1   rw   	  s    z/_import_openssh_private_rsa.<locals>.<listcomp>)_opensshr   r   r   r   r    r   )datapasswordr   r   r   r   ssh_name	decryptedr   r   r   iqmpr   r   r   paddedbuildr0   r0   r1   _import_openssh_private_rsa  s   r  c                 C   sV  ddl m} t| } |durt|}| dr+t| }|||\}}}t||}|S | drD|t| |\}}}|r?d}t||S | drt	| 
dd }	g }
t|	d	krtd
|	dd	 d }|
|	d	d	|   |	d	| d }	t|	d	ks[t|
d }t|
d }t||gS t| dkrt| d dkrt| |S td)a  Import an RSA key (public or private).

    Args:
      extern_key (string or byte string):
        The RSA key to import.

        The following formats are supported for an RSA **public key**:

        - X.509 certificate (binary or PEM format)
        - X.509 ``subjectPublicKeyInfo`` DER SEQUENCE (binary or PEM
          encoding)
        - `PKCS#1`_ ``RSAPublicKey`` DER SEQUENCE (binary or PEM encoding)
        - An OpenSSH line (e.g. the content of ``~/.ssh/id_ecdsa``, ASCII)

        The following formats are supported for an RSA **private key**:

        - PKCS#1 ``RSAPrivateKey`` DER SEQUENCE (binary or PEM encoding)
        - `PKCS#8`_ ``PrivateKeyInfo`` or ``EncryptedPrivateKeyInfo``
          DER SEQUENCE (binary or PEM encoding)
        - OpenSSH (text format, introduced in `OpenSSH 6.5`_)

        For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.

      passphrase (string or byte string):
        For private keys only, the pass phrase that encrypts the key.

    Returns: An RSA key object (:class:`RsaKey`).

    Raises:
      ValueError/IndexError/TypeError:
        When the given key cannot be parsed (possibly because the pass
        phrase is wrong).

    .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
    .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
    .. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt
    .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
    .. _`OpenSSH 6.5`: https://flak.tedunangst.com/post/new-openssh-key-format-and-bcrypt-pbkdf
    r   r   Ns   -----BEGIN OPENSSH PRIVATE KEYs   -----r       r   r   r{   r   0   r   )r   rq   r   
startswithr
   r   r  r   r   
a2b_base64splitr~   r|   unpackappendr   r   r   r	   r    )r   r   rq   text_encodedopenssh_encodedmarkerenc_flagrW   r   r   r   lengthr   r   r0   r0   r1   r     s8   )





r   z1.2.840.113549.1.1.1)Nr   )Tr4   )&__all__r   r|   Cryptor   Crypto.Util.py3compatr   r	   r
   Crypto.Util.asn1r   r   Crypto.Util.numberr   Crypto.Math.Numbersr   Crypto.Math.Primalityr   r   r   Crypto.PublicKeyr   r   r   r   r   r   r   r   r   r   r   r   r   r  r   	importKeyr   r0   r0   r0   r1   <module>   s6      

R 	

P
