3
¬ �e«x  ã               @   s   d ddddg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               @   sR  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dKd7d8„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 |jƒ ƒ}t dƒ}|t dƒB }|||fkr4tdƒ‚x$|jƒ D ]\}}t| d| |ƒ q>W ||krŒ| j| jd	  | _| j| jd	  | _	d
| _
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)r   r   )r   r   r   r   )ÚsetÚkeysÚ
ValueErrorÚitemsÚsetattrÚ_dÚ_pÚ_dpÚ_qÚ_dqÚ_invq)ÚselfÚkwargsZ	input_setZ
public_setZprivate_setZ	componentÚvalue© r+   ú[/var/www/html/wholesaler-api-python-env/lib/python3.6/site-packages/Crypto/PublicKey/RSA.pyÚ__init__R   s    zRsaKey.__init__c             C   s
   t | jƒS )N)ÚintÚ_n)r(   r+   r+   r,   r   q   s    zRsaKey.nc             C   s
   t | jƒS )N)r.   Ú_e)r(   r+   r+   r,   r   u   s    zRsaKey.ec             C   s   | j ƒ stdƒ‚t| jƒS )Nz-No private exponent available for public keys)Úhas_privateÚAttributeErrorr.   r"   )r(   r+   r+   r,   r   y   s    zRsaKey.dc             C   s   | j ƒ stdƒ‚t| jƒS )Nz.No CRT component 'p' available for public keys)r1   r2   r.   r#   )r(   r+   r+   r,   r      s    zRsaKey.pc             C   s   | j ƒ stdƒ‚t| jƒS )Nz.No CRT component 'q' available for public keys)r1   r2   r.   r%   )r(   r+   r+   r,   r   …   s    zRsaKey.qc             C   s   | j ƒ stdƒ‚t| jƒS )Nz/No CRT component 'dp' available for public keys)r1   r2   r.   r$   )r(   r+   r+   r,   Údp‹   s    z	RsaKey.dpc             C   s   | j ƒ stdƒ‚t| jƒS )Nz/No CRT component 'dq' available for public keys)r1   r2   r.   r&   )r(   r+   r+   r,   Údq‘   s    z	RsaKey.dqc             C   s4   | j ƒ stdƒ‚| jd kr*| jj| jƒ| _t| jƒS )Nz1No CRT component 'invq' available for public keys)r1   r2   r'   r%   Úinverser#   r.   )r(   r+   r+   r,   Úinvq—   s
    
zRsaKey.invqc             C   s   | j S )N)r   )r(   r+   r+   r,   ÚinvpŸ   s    zRsaKey.invpc             C   s   | j ƒ stdƒ‚t| jƒS )Nz.No CRT component 'u' available for public keys)r1   r2   r.   Ú_u)r(   r+   r+   r,   r   £   s    zRsaKey.uc             C   s
   | j jƒ S )zSize of the RSA modulus in bits)r/   Úsize_in_bits)r(   r+   r+   r,   r9   ©   s    zRsaKey.size_in_bitsc             C   s   | j jƒ d d d S )z9The minimal amount of bytes that can hold the RSA modulusr   é   )r/   r9   )r(   r+   r+   r,   Úsize_in_bytes­   s    zRsaKey.size_in_bytesc             C   s:   d|  ko| j k n  s"tdƒ‚ttt|ƒ| j| j ƒƒS )Nr   zPlaintext too large)r/   r   r.   Úpowr   r0   )r(   Ú	plaintextr+   r+   r,   Ú_encrypt±   s    zRsaKey._encryptc       	      C   s¾   d|  ko| j k n  s"tdƒ‚| jƒ s2tdƒ‚tjd| j d�}t|ƒt|| j| j ƒ | j  }t|| j| j	ƒ}t|| j
| jƒ}|| | j | j }|| j	 | }tj|j| j ƒ|| j ƒ}|S )Nr   zCiphertext too largezThis is not a private keyr   )Zmin_inclusiveZmax_exclusive)r/   r   r1   Ú	TypeErrorr   Zrandom_ranger<   r0   r$   r#   r&   r%   r8   Z_mult_modulo_bytesr5   )	r(   Ú
ciphertextÚrZcpÚm1Úm2ÚhÚmpÚresultr+   r+   r,   Ú_decrypt_to_bytes¶   s    
zRsaKey._decrypt_to_bytesc             C   s   t | j|ƒƒS )zLegacy private method)r   rG   )r(   r@   r+   r+   r,   Ú_decryptÏ   s    zRsaKey._decryptc             C   s
   t | dƒS )z"Whether this is an RSA private keyr"   )Úhasattr)r(   r+   r+   r,   r1   Ô   s    zRsaKey.has_privatec             C   s   dS )NTr+   )r(   r+   r+   r,   Úcan_encryptÙ   s    zRsaKey.can_encryptc             C   s   dS )NTr+   )r(   r+   r+   r,   Úcan_signÜ   s    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   )r   r/   r0   )r(   r+   r+   r,   Ú
public_keyß   s    zRsaKey.public_keyc             C   sH   | j ƒ |j ƒ krdS | j|jks,| j|jkr0dS | j ƒ s<dS | j|jkS )NFT)r1   r   r   r   )r(   Úotherr+   r+   r,   Ú__eq__ç   s    zRsaKey.__eq__c             C   s
   | |k S )Nr+   )r(   rM   r+   r+   r,   Ú__ne__ð   s    zRsaKey.__ne__c             C   s   ddl m} |‚d S )Nr   )ÚPicklingError)ÚpicklerP   )r(   rP   r+   r+   r,   Ú__getstate__ó   s    zRsaKey.__getstate__c             C   sP   | j ƒ r2d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))r1   r.   r"   r#   r%   r8   r/   r0   )r(   Úextrar+   r+   r,   Ú__repr__ø   s
    zRsaKey.__repr__c             C   s"   | j ƒ rd}nd}d|t| ƒf S )NZPrivateZPublicz%s RSA key at 0x%X)r1   Úid)r(   Úkey_typer+   r+   r,   Ú__str__   s    zRsaKey.__str__ÚPEMNr   c             C   s  |dk	rt |ƒ}|dkrtj}|dkr¤dd„ | j| jfD ƒ\}}t|d ƒd@ rXd| }t|d ƒd@ rpd| }d||g}	d	jd
d„ |	D ƒƒ}
dtj|
ƒdd…  S | j	ƒ �r˜t
d| j| j| j| j| j| j| jd  | j| jd  t| jƒj| jƒg	ƒjƒ }|dk�r$d}|dk�r–|�r–tdƒ‚nrddlm} |dk�r^|dk�r^d}|j|tdtƒ d�}n8d}|�sz|�rvtdƒ‚d}|j|t|||tƒ d�}d}nd}ttt
| j| jgƒtƒ ƒ}|dk�rÄ|S |dk�ròddlm} |j||||ƒ}t |ƒS td| ƒ‚dS )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
        NZOpenSSHc             S   s   g | ]}|j ƒ ‘qS r+   )Úto_bytes)Ú.0Úxr+   r+   r,   ú
<listcomp>d  s    z%RsaKey.export_key.<locals>.<listcomp>r   é€   ó    s   ssh-rsaó    c             S   s    g | ]}t jd t|ƒƒ| ‘qS )z>I)ÚstructÚpackÚlen)r[   Zkpr+   r+   r,   r]   j  s    s   ssh-rsa r   zRSA PRIVATE KEYZDERz&PKCS#1 private key cannot be encrypted)ÚPKCS8rY   zPRIVATE KEY)Ú
key_paramszENCRYPTED PRIVATE KEYz"'protection' parameter must be setz"PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC)Úprot_paramsre   z
PUBLIC KEY)rY   z3Unknown key format '%s'. Cannot export the RSA key.éÿÿÿÿ)r   r   Úget_random_bytesr0   r/   r	   ÚjoinÚbinasciiÚ
b2a_base64r1   r   r   r   r   r   r   r   r5   Úencoder   Ú	Crypto.IOrd   Úwrapr   r   r   rY   )r(   ÚformatÚ
passphraseZpkcsZ
protectionÚrandfuncrf   Ze_bytesZn_bytesÚkeypartsÚ	keystringZ
binary_keyrW   rd   rY   Zpem_strr+   r+   r,   Ú
export_key  sl    V







zRsaKey.export_keyc             O   s   | j ||ŽS )z:meta private:)rt   )r(   Úargsr)   r+   r+   r,   Ú	exportKey£  s    zRsaKey.exportKeyc             C   s   | j ƒ S )z:meta private:)rL   )r(   r+   r+   r,   Ú	publickey§  s    zRsaKey.publickeyc             C   s   t dƒ‚dS )z:meta private:z,Use module Crypto.Signature.pkcs1_15 insteadN)ÚNotImplementedError)r(   ÚMÚKr+   r+   r,   Úsign¬  s    zRsaKey.signc             C   s   t dƒ‚dS )z:meta private:z,Use module Crypto.Signature.pkcs1_15 insteadN)rx   )r(   ry   Ú	signaturer+   r+   r,   Úverify°  s    zRsaKey.verifyc             C   s   t dƒ‚dS )z:meta private:z+Use module Crypto.Cipher.PKCS1_OAEP insteadN)rx   )r(   r=   rz   r+   r+   r,   Úencrypt´  s    zRsaKey.encryptc             C   s   t dƒ‚dS )z:meta private:z+Use module Crypto.Cipher.PKCS1_OAEP insteadN)rx   )r(   r@   r+   r+   r,   Údecrypt¸  s    zRsaKey.decryptc             C   s   t ‚dS )z:meta private:N)rx   )r(   ry   ÚBr+   r+   r,   Úblind¼  s    zRsaKey.blindc             C   s   t ‚dS )z:meta private:N)rx   )r(   ry   r€   r+   r+   r,   ÚunblindÀ  s    zRsaKey.unblindc             C   s   t ‚dS )z:meta private:N)rx   )r(   r+   r+   r,   ÚsizeÄ  s    zRsaKey.size)rY   Nr   NNN)(Ú__name__Ú
__module__Ú__qualname__Ú__doc__r-   Úpropertyr   r   r   r   r   r3   r4   r6   r7   r   r9   r;   r>   rG   rH   r1   rJ   rK   rL   rN   rO   rR   rU   rX   rt   rv   rw   r{   r}   r~   r   r�   r‚   rƒ   r+   r+   r+   r,   r   4   sL   	 
 é  c                sd  | dk rt dƒ‚ˆ d dks$ˆ dk r,t dƒ‚|dkr:tj}tdƒ }}tˆ ƒ‰ xâ|jƒ | koj|d| d > k �r0| d }| | }tdƒd| d > jƒ  ‰‰||krºtdƒd| d > jƒ ‰‡ ‡fd	d
„}t|||d�‰tdƒ| d d > ‰‡ ‡‡‡fdd„}t|||d�}	ˆ|	 }ˆd j|	d ƒ}
ˆ j|
ƒ}qPW ˆ|	k�rF|	ˆ ‰}	ˆj|	ƒ}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 j ˆ ƒdkS )Nr   )Úgcd)Ú	candidate)r   Úmin_pr+   r,   Úfilter_pý  s    zgenerate.<locals>.filter_p)Z
exact_bitsrq   Zprime_filteréd   c                s*   | ˆko(| d j ˆ ƒdko(t| ˆ ƒˆkS )Nr   )rŒ   Úabs)r�   )r   Úmin_distanceÚmin_qr   r+   r,   Úfilter_q  s    zgenerate.<locals>.filter_q)r   r   r   r   r   r   )
r   r   rh   r   r9   Úsqrtr   Úlcmr5   r   )Úbitsrq   r   r   r   Zsize_qZsize_pr�   r”   r   r–   r   r+   )r   r’   rŽ   r“   r   r,   r   É  s<     


Tc             C   sü  G dd„ dt ƒ}|ƒ }x&td| ƒD ]\}}t||t|ƒƒ q"W |j}|j}t|dƒsdt||d	�}�n:|j}	t|dƒr‚|j	}
|j
}nê|	| d
 }|}x|d dkrª|d }q”W d}tdƒ}xŠ| oÆ|dk �rBt|ƒ}xd||k �r6t|||ƒ}|d
k�r,||d
 k�r,t|d|ƒd
k�r,t|ƒj|d
 ƒ}
d}P |d9 }qÔW |d7 }qºW |�sRtdƒ‚||
 dk�sdt‚||
 }t|dƒ�r€|j}n
|
j|ƒ}t|||	|
||d�}|�rø|d
k�s¸||k�rÀtdƒ‚t|ƒj|ƒd
k�rÜtdƒ‚|d
@ �sîtdƒ‚|jƒ �rø|	d
k�s|	|k�rtdƒ‚t|ƒj|	ƒd
k�r0tdƒ‚|
| |k�rFtdƒ‚t|
ƒtk�r\tdƒ‚t|ƒtk�rrtdƒ‚|
d
 |d
  }||
d
 j|d
 ƒ }||	 t|ƒ d
k�r¶tdƒ‚t|dƒ�rø|d
k�sÖ||k�rÞtdƒ‚|
| | d
k�røt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†   r+   r+   r+   r,   Ú
InputCompsD  s   r˜   r   r   r   r   r   r   )r   r   r   rŠ   r   Fr�   Tz2Unable to compute factors p and q from exponent d.)r   r   r   r   r   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)r   r   r   r   r   r   )ÚobjectÚzipr!   r   r   r   rI   r   r   r   r   r<   rŒ   r   ÚAssertionErrorr   r5   r1   r   r   r.   )Zrsa_componentsZconsistency_checkr˜   Zinput_compsÚcompr*   r   r   Úkeyr   r   r   ZktotÚtZspottedÚaÚkZcandr   Úphir–   r+   r+   r,   r     s€    )

*


c             G   sN   t ƒ j| ddd�}|d dkr&tdƒ‚t|dd… t|d ƒj|d	 ƒg ƒS )
Né	   T)Únr_elementsÚonly_ints_expectedr   z(No PKCS#1 encoding of an RSA private keyr   é   é   é   )r   Údecoder   r   r   r5   )Úencodedr)   Úderr+   r+   r,   Ú_import_pkcs1_private«  s    r«   c             G   s   t ƒ j| ddd�}t|ƒS )NrŠ   T)r£   r¤   )r   r¨   r   )r©   r)   rª   r+   r+   r,   Ú_import_pkcs1_public¿  s    r¬   c             G   s.   t | ƒ\}}}|tks|d k	r&tdƒ‚t|ƒS )NzNo RSA subjectPublicKeyInfo)r   r   r   r¬   )r©   r)   ZalgoidZencoded_keyÚparamsr+   r+   r,   Ú_import_subjectPublicKeyInfoÈ  s    r®   c             G   s   t | ƒ}t|ƒS )N)r   r®   )r©   r)   Zsp_infor+   r+   r,   Ú_import_x509_certÐ  s    r¯   c             C   s:   ddl m} |j| |ƒ}|d tkr,tdƒ‚t|d |ƒS )Nr   )rd   zNo PKCS#8 encoded RSA keyr   )rm   rd   Úunwrapr   r   Ú_import_keyDER)r©   rp   rd   r    r+   r+   r,   Ú_import_pkcs8Ö  s
    r²   c             C   sH   t ttttf}x,|D ]$}y
|| |ƒS  tk
r6   Y qX qW tdƒ‚dS )z@Import an RSA key (public or private half), encoded in DER form.zRSA key format is not supportedN)r«   r¬   r®   r¯   r²   r   )Ú
extern_keyrp   Z	decodingsZdecodingr+   r+   r,   r±   ß  s    


r±   c             C   s´   ddl m}m}m}m} || |ƒ\}}|dkr6t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 j|ƒ‘qS r+   )r   Ú
from_bytes)r[   r\   r+   r+   r,   r]     s    z/_import_openssh_private_rsa.<locals>.<listcomp>)Z_opensshr´   rµ   r¶   r·   r   r   )ÚdataÚpasswordr´   rµ   r¶   r·   Zssh_nameZ	decryptedr   r   r   Ziqmpr   r   r   ZpaddedÚbuildr+   r+   r,   Ú_import_openssh_private_rsañ  s    r¼   c             C   sZ  ddl m} t| ƒ} |dk	r$t|ƒ}| jdƒrVt| ƒ}|j||ƒ\}}}t||ƒ}|S | jdƒrˆ|jt| ƒ|ƒ\}}}|r~d}t||ƒS | jdƒ�r$tj	| j
dƒd ƒ}	g }
xNt|	ƒd	krútjd
|	dd	… ƒd }|
j|	d	d	| … ƒ |	d	| d… }	q®W tj|
d ƒ}tj|
d ƒ}t||gƒS t| ƒdk�rNt| d ƒdk�rNt| |ƒS tdƒ‚dS )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   )rY   Ns   -----BEGIN OPENSSH PRIVATE KEYs   -----s   ssh-rsa ó    r   r¦   z>IrŠ   é0   zRSA key format is not supported)rm   rY   r   Ú
startswithr
   r¨   r¼   r±   rj   Ú
a2b_base64Úsplitrc   ra   ÚunpackÚappendr   r¸   r   r	   r   )r³   rp   rY   Ztext_encodedZopenssh_encodedÚmarkerZenc_flagrF   rª   rs   rr   Úlengthr   r   r+   r+   r,   r   	  s6    )



 
z1.2.840.113549.1.1.1)Nr‰   )T)N)&Ú__all__rj   ra   ÚCryptor   ZCrypto.Util.py3compatr   r	   r
   ZCrypto.Util.asn1r   r   ZCrypto.Util.numberr   ZCrypto.Math.Numbersr   ZCrypto.Math.Primalityr   r   r   ZCrypto.PublicKeyr   r   r   r™   r   r   r   r«   r¬   r®   r¯   r²   r±   r¼   r   Z	importKeyr   r+   r+   r+   r,   Ú<module>    s6      
R
 		
P