U +Mbp@sdddddgZddlZddlZddlmZddlmZmZmZdd l m Z dd l m Z dd l mZmZmZdd lmZmZmZGd ddeZd"ddZd#ddZddZddZddZddZddZddZddZd$d dZ e Z!d!Z"dS)%generate construct import_keyRsaKeyoidN)Random)tobytesbordtostr) DerSequence)Integer)test_probable_primegenerate_probable_prime COMPOSITE)_expand_subject_public_key_info_create_subject_public_key_info _extract_subject_public_key_infoc@seZdZdZddZeddZeddZedd Zed d Z ed d Z eddZ ddZ ddZ ddZddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd=d-d.ZeZeZd/d0Zd1d2Zd3d4Zd5d6Zd7d8Z d9d:Z!d;d<Z"d+S)>raPClass defining an actual RSA key. 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 u: Chinese remainder component (:math:`p^{-1} \text{mod } q`) :vartype u: integer :undocumented: exportKey, publickey cKst|}td}|tdB}|||fkr4td|D]\}}t|d||q<||kr|j|jd|_|j|jd|_ dS)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. ne)pqduzSome RSA components are missing_N) setkeys ValueErroritemssetattr_d_p_dp_q_dq)selfkwargsZ input_setZ public_setZ private_set componentvaluer*;/tmp/pip-target-t616c12r/lib/python/Crypto/PublicKey/RSA.py__init__Ms   zRsaKey.__init__cCs t|jSN)int_nr&r*r*r+rkszRsaKey.ncCs t|jSr-)r._er0r*r*r+roszRsaKey.ecCs|stdt|jS)Nz-No private exponent available for public keys) has_privateAttributeErrorr.r!r0r*r*r+rsszRsaKey.dcCs|stdt|jS)Nz.No CRT component 'p' available for public keys)r2r3r.r"r0r*r*r+ryszRsaKey.pcCs|stdt|jS)Nz.No CRT component 'q' available for public keys)r2r3r.r$r0r*r*r+rszRsaKey.qcCs|stdt|jS)Nz.No CRT component 'u' available for public keys)r2r3r._ur0r*r*r+rszRsaKey.ucCs |jS)zSize of the RSA modulus in bitsr/ size_in_bitsr0r*r*r+r6szRsaKey.size_in_bitscCs|jdddS)z9The minimal amount of bytes that can hold the RSA modulusrr5r0r*r*r+ size_in_bytesszRsaKey.size_in_bytescCs8d|kr|jks ntdttt||j|jS)NrzPlaintext too large)r/rr.powr r1)r& plaintextr*r*r+_encryptszRsaKey._encryptc Csd|kr|jks ntd|s0tdtjd|jd}t|t||j|j|j}t||j|j }t||j |j }|||j |j }||j |}| |j||j}|t||j|jkrtd|S)NrzCiphertext too largezThis is not a private keyr)Z min_inclusiveZ max_exclusivez Fault detected in RSA decryption)r/rr2 TypeErrorr Z random_ranger9r1r#r"r%r$r4inverse) r& ciphertextrcpm1m2hmpresultr*r*r+_decryptszRsaKey._decryptcCs t|dS)z"Whether this is an RSA private keyr!)hasattrr0r*r*r+r2szRsaKey.has_privatecCsdSNTr*r0r*r*r+ can_encryptszRsaKey.can_encryptcCsdSrHr*r0r*r*r+can_signszRsaKey.can_signcCst|j|jdS)z^A matching RSA public key. Returns: a new :class:`RsaKey` object r)rr/r1r0r*r*r+ public_keyszRsaKey.public_keycCsH||krdS|j|jks,|j|jkr0dS|s7sz%RsaKey.export_key..rsssh-rsacSs g|]}tdt||qS)>I)structpacklen)r\kpr*r*r+r^=sssh-rsa rzRSA PRIVATE KEYZDERz&PKCS#1 private key cannot be encryptedPKCS8rYz PRIVATE KEYzENCRYPTED PRIVATE KEYz"PBKDF2WithHMAC-SHA1AndDES-EDE3-CBCz PUBLIC KEYrYz3Unknown key format '%s'. Cannot export the RSA key.)rrget_random_bytesr1r/r joinbinascii b2a_base64r2r rrrrrr r=encoder Crypto.IOrjwraprrrY)r&format passphraseZpkcsZ protectionrandfuncZe_bytesZn_byteskeyparts keystringZ binary_keyrWrjrYZpem_strr*r*r+ export_keysjM        zRsaKey.export_keycCs tddSNz,Use module Crypto.Signature.pkcs1_15 insteadNotImplementedError)r&MKr*r*r+signtsz RsaKey.signcCs tddSryrz)r&r| signaturer*r*r+verifywsz RsaKey.verifycCs tddSNz+Use module Crypto.Cipher.PKCS1_OAEP insteadrz)r&r:r}r*r*r+encryptzszRsaKey.encryptcCs tddSrrz)r&r>r*r*r+decrypt}szRsaKey.decryptcCstdSr-rzr&r|Br*r*r+blindsz RsaKey.blindcCstdSr-rzrr*r*r+unblindszRsaKey.unblindcCstdSr-rzr0r*r*r+sizesz RsaKey.size)rYNrNN)#__name__ __module__ __qualname____doc__r,propertyrrrrrrr6r8r;rFr2rIrJrKrNrOrRrUrXrxZ exportKeyZ publickeyr~rrrrrrr*r*r*r+r3sR        c sb|dkrtdddks$dkr,td|dkr:tj}td}}t||kr0|d|d>kr0|d}||}tdd|d>||krtdd|d>fd d }t|||d td|dd >fd d}t|||d } | }d| d} | }qN| krD| } | } t ||| | dS)a0Create 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. 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 iz"RSA modulus length must be >= 1024rzBRSA public exponent must be a positive, odd integer larger than 2.Nrcs|ko|ddkSNr)gcd candidate)rmin_pr*r+filter_pszgenerate..filter_p)Z exact_bitsruZ prime_filterdcs*|ko(|ddko(t|kSr)rabsr)r min_distancemin_qrr*r+filter_qs zgenerate..filter_qrrrrrr) rrrlr r6sqrtrlcmr=r) bitsrurrrZsize_qZsize_prrrrrr*)rrrrrr+rs@      TcCsGdddt}|}td|D]\}}t||t|q |j}|j}t|ds`t||d}n0|j} t|dr~|j } |j } n| |d} | } | dd kr| d} qd }td}|s6|d kr6t| }|| kr,t |||}|dkr"||dkr"t |d|dkr"t| |d} d }q,|d9}q|d7}q|sDt d || d ksVt|| } t|drr|j}n | | }t||| | | |d}|r|dks||krt dt| |dkrt d|d@st d|r| dks| |krt dt| | dkr"t d| | |kr8t dt| tkrNt dt| tkrdt d| d| d}|| d | d}|| t|dkrt dt|dr|dks|| krt d| || dkrt d|S)a!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. 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 eZdZdS)zconstruct..InputCompsN)rrrr*r*r*r+ InputCompssrrrrrrrrFrTz2Unable to compute factors p and q from exponent d.rzInvalid RSA public exponentz-RSA public exponent is not coprime to moduluszRSA modulus is not oddzInvalid RSA private exponentz.RSA private exponent is not coprime to modulusz RSA factors do not match moduluszRSA factor p is compositezRSA factor q is compositezInvalid RSA conditionzInvalid RSA component uzInvalid RSA component u with p)objectzipr r rrrGrrrrr9rrAssertionErrorrr=r2r rr.)Zrsa_componentsZconsistency_checkrZ input_compscompr)rrkeyrrrZktottZspottedakcandrphirr*r*r+rs(       *       cGsNtj|ddd}|ddkr&tdt|ddt|d|d gS) N TZ nr_elementsZonly_ints_expectedrz(No PKCS#1 encoding of an RSA private keyr)r decoderrr r=encodedr'derr*r*r+_import_pkcs1_privatejs rcGstj|ddd}t|S)NrTr)r rrrr*r*r+_import_pkcs1_public~srcGs.t|\}}}|tks|dk r&tdt|S)NzNo RSA subjectPublicKeyInfo)rrrr)rr'ZalgoidZ encoded_keyparamsr*r*r+_import_subjectPublicKeyInfosrcGst|}t|Sr-)rr)rr'Zsp_infor*r*r+_import_x509_certsrcCs:ddlm}|||}|dtkr,tdt|d|S)NrrizNo PKCS#8 encoded RSA keyr)rqrjunwraprr_import_keyDER)rrtrjrr*r*r+ _import_pkcs8s    rc CsJtttttf}|D]*}z|||WStk r:YqXqtddS)z@Import an RSA key (public or private half), encoded in DER form.RSA key format is not supportedN)rrrrrr) extern_keyrtZ decodingsZdecodingr*r*r+rsrcCsddlm}m}m}m}|||\}}|dkr6td||\}}||\} }||\} }||\} }||\} }||\} }||\}}||dd|| | | | | fD}t|S)Nr)import_openssh_private_generic read_bytes read_string check_paddingzssh-rsazThis SSH key is not RSAcSsg|]}t|qSr*)r from_bytesr[r*r*r+r^sz/_import_openssh_private_rsa..)Z_opensshrrrrrr)datapasswordrrrrZssh_nameZ decryptedrrrZiqmprrrpaddedbuildr*r*r+_import_openssh_private_rsas       rcCsVddlm}t|}|dk r$t|}|drVt|}|||\}}}t||}|S|dr|t||\}}}|r~d}t||S|dr t | dd} g} t | d krt d | dd d} | | d d | | d | d} qt| d} t| d } t| | gSt |dkrJt|dd krJt||Std dS)aImport 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 rrkNs-----BEGIN OPENSSH PRIVATE KEYs-----rg rrrbr0r)rqrYr startswithr rrrrn a2b_base64splitrercunpackappendr rrr r)rrtrYZ text_encodedZopenssh_encodedmarkerZenc_flagrErrwrvlengthrrr*r*r+rs6)          z1.2.840.113549.1.1.1)Nr)T)N)#__all__rnrcZCryptorZCrypto.Util.py3compatrr r ZCrypto.Util.asn1r ZCrypto.Math.Numbersr ZCrypto.Math.Primalityr rrZCrypto.PublicKeyrrrrrrrrrrrrrrrZ importKeyrr*r*r*r+ s6   Y Q    P