3 M(ÌYSYã @sVdZddlZddlmZddlZddlZddlZddlZddl Zej e ƒZ dZ Gdd„deƒZGdd„deƒZGd d „d eƒZejjd fd d „Zdd„Zdd„Zd e fdd„Zd de fdd„Zdd dgZe dk�rRddlZyPxJedƒD]>Zejƒ\ZZerüPe�reddk�sedkræe deƒqæWWne!k �rHe dƒYn Xe dƒdS)ajRSA 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)Úbic@sPeZdZdZdZdd„Zeddd„ƒZed d „ƒZ dd d „Z d d„Z dd„Z dS)Ú AbstractKeyz0Abstract superclass for private and public keys.ÚnÚecCs||_||_dS)N)rr)Úselfrr©rú./private/tmp/pip-build-nl73fm5q/rsa/rsa/key.pyÚ__init__6szAbstractKey.__init__ÚPEMcCs"|j|jdœ}|j||ƒ}||ƒS)aLoads 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 ÚDER)Ú_load_pkcs1_pemÚ_load_pkcs1_derÚ_assert_format_exists)ÚclsÚkeyfileÚformatÚmethodsÚmethodrrrÚ load_pkcs1:s   zAbstractKey.load_pkcs1c CsDy||Stk r>djt|jƒƒƒ}td||fƒ‚YnXdS)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ÚformatsrrrrMs z!AbstractKey._assert_format_existscCs |j|jdœ}|j||ƒ}|ƒS)z«Saves 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 r )Ú_save_pkcs1_pemÚ_save_pkcs1_derr)rrrrrrrÚ save_pkcs1Ys  zAbstractKey.save_pkcs1cCs|t||j|jƒ|jS)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 )Úpowrr)rÚmessageÚrrrrÚblindhszAbstractKey.blindcCstjj||jƒ||jS)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 rrrÚunblindys zAbstractKey.unblindN)rr)r )r ) Ú__name__Ú __module__Ú __qualname__Ú__doc__Ú __slots__r Ú classmethodrÚ staticmethodrrr!r&rrrrr1s  rc@s„eZdZdZdZdd„Zdd„Zdd „Zd d „Zd d „Z dd„Z e dd„ƒZ dd„Z e dd„ƒZdd„Ze dd„ƒZe dd„ƒZdS)Ú 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 rrcCs t||ƒS)N)Úgetattr)rÚkeyrrrÚ __getitem__¢szPublicKey.__getitem__cCsd|j|jfS)NzPublicKey(%i, %i))rr)rrrrÚ__repr__¥szPublicKey.__repr__cCs |j|jfS)z&Returns the key as tuple for pickling.)rr)rrrrÚ __getstate__¨szPublicKey.__getstate__cCs|\|_|_dS)zSets the key from tuple.N)rr)rÚstaterrrÚ __setstate__¬szPublicKey.__setstate__cCs2|dkr dSt|tƒsdS|j|jko0|j|jkS)NF)Ú isinstancer.rr)rÚotherrrrÚ__eq__°s  zPublicKey.__eq__cCs ||k S)Nr)rr7rrrÚ__ne__¹szPublicKey.__ne__cCsHddlm}ddlm}|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ÚpublicExponent)rr)Úpyasn1.codec.derr:Úrsa.asn1r;ÚdecodeÚint)rrr:r;ÚprivÚ_rrrr ¼s  zPublicKey._load_pkcs1_dercCsDddlm}ddlm}|ƒ}|jd|jƒ|jd|jƒ|j|ƒS)zbSaves the public key in PKCS#1 DER format. @returns: the DER-encoded public key. r)Úencoder)r;r=r>)r?rEr@r;ÚsetComponentByNamerrÚencode)rrEr;Úasn_keyrrrr×s   zPublicKey._save_pkcs1_dercCstjj|dƒ}|j|ƒS)aOLoads 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 zRSA PUBLIC KEY)r"ÚpemÚload_pemr )rrÚderrrrr çs zPublicKey._load_pkcs1_pemcCs|jƒ}tjj|dƒS)zƒSaves a PKCS#1 PEM-encoded public key file. :return: contents of a PEM-encoded file that contains the public key. zRSA PUBLIC KEY)rr"rIÚsave_pem)rrKrrrröszPublicKey._save_pkcs1_pemcCstjj|dƒ}|j|ƒ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"rIrJÚload_pkcs1_openssl_der)rrrKrrrÚload_pkcs1_openssl_pemÿsz PublicKey.load_pkcs1_openssl_pemcCslddlm}ddlm}ddlm}|j||ƒd�\}}|dd|jdƒkrVtd ƒ‚|j |d d d …ƒS) zÖLoads 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)Ú OpenSSLPubKey)r:)Úuniv)r<ÚheaderÚoidz1.2.840.113549.1.1.1z7This is not a DER-encoded OpenSSL-compatible public keyr0éN) r@rOr?r:Ú pyasn1.typerPrAZObjectIdentifierÚ TypeErrorr )rrrOr:rPZkeyinforDrrrrMs   z PublicKey.load_pkcs1_openssl_derN)rr)r'r(r)r*r+r1r2r3r5r8r9r,r rr rrNrMrrrrr.ˆs    r.c@s†eZdZdZd%Zd&d d „Zd d„Zdd„Zdd„Zdd„Z dd„Z dd„Z dd„Z dd„Z edd„ƒZdd „Zed!d"„ƒZd#d$„Zd 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 rrÚdÚpÚqÚexp1Úexp2ÚcoefNc Csˆtj|||ƒ||_||_||_|dkrtjj|jdƒ}|j||ƒ}tjj||j|jƒ}|j||ƒS)zØDecrypts the message using blinding to prevent side-channel attacks. :param encrypted: the encrypted message :type encrypted: int :returns: the decrypted message :rtype: int rS) r"ÚrandnumÚrandintrr!ÚcoreZ decrypt_intrWr&)rÚ encryptedÚblind_rr%Z decryptedrrrÚblinded_decrypt‚s  zPrivateKey.blinded_decryptcCs>tjj|jdƒ}|j||ƒ}tjj||j|jƒ}|j||ƒS)zÕEncrypts the message using blinding to prevent side-channel attacks. :param message: the message to encrypt :type message: int :returns: the encrypted message :rtype: int rS) r"r]r^rr!r_Z encrypt_intrWr&)rrrar%r`rrrÚblinded_encrypt’s  zPrivateKey.blinded_encryptcCsXddlm}|j|ƒ\}}|ddkr6td|dƒ‚tdd„|dd…Dƒƒ}||ŽS)aLoads 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)r:z)Unable to read this file, version %s != 0css|]}t|ƒVqdS)N)rB)Ú.0Úxrrrú Ësz-PrivateKey._load_pkcs1_der..rSé )r?r:rArÚtuple)rrr:rCrDZas_intsrrrr ¡s   zPrivateKey._load_pkcs1_dercsÀddlm‰m‰ddlm}G‡‡fdd„dˆjƒ}|ƒ}|jddƒ|jd|jƒ|jd|jƒ|jd |j ƒ|jd |j ƒ|jd |j ƒ|jd |j ƒ|jd |j ƒ|jd|jƒ|j|ƒS)zdSaves the private key in PKCS#1 DER format. @returns: the DER-encoded private key. r)rPÚ namedtype)rEc s’eZdZ”j”jd”jƒƒ”jd”jƒƒ”jd”jƒƒ”jd”jƒƒ”jd”jƒƒ”jd”jƒƒ”jd”jƒƒ”jd”jƒƒ”jd ”jƒƒƒ Zd S) z.PrivateKey._save_pkcs1_der..AsnPrivKeyÚversionr=r>ÚprivateExponentÚprime1Úprime2Ú exponent1Ú exponent2Ú coefficientN)r'r(r)Z NamedTypesZ NamedTypeZIntegerZ componentTyper)rirPrrÚ AsnPrivKey×srqrjr=r>rkrlrmrnrorp)rTrPrir?rEÚSequencerFrrrWrXrYrZr[r\rG)rrErqrHr)rirPrrÎs  zPrivateKey._save_pkcs1_dercCstjj|tdƒƒ}|j|ƒS)aTLoads 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 zRSA PRIVATE KEY)r"rIrJrr )rrrKrrrr òs zPrivateKey._load_pkcs1_pemcCs|jƒ}tjj|tdƒƒS)z…Saves a PKCS#1 PEM-encoded private key file. :return: contents of a PEM-encoded file that contains the private key. zRSA PRIVATE KEY)rr"rIrLr)rrKrrrrszPrivateKey._save_pkcs1_pem)rrrWrXrYrZr[r\)NNN)r'r(r)r*r+r r1r2r3r5r8r9rbrcr,r rr rrrrrrV's   -$ rVTc sš|d‰|d}||}||}tjd|ƒ||ƒ}tjd|ƒ||ƒ}‡‡fdd„}d} x*|||ƒs„| rt||ƒ}n||ƒ}| } q\Wt||ƒt||ƒfS)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 éézfind_p_q(%i): Finding pzfind_p_q(%i): Finding qcs,||kr dSˆsdStjj||ƒ}ˆ|kS)z“Returns 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#Zbit_size)rXrYZ found_size)ÚaccurateÚ total_bitsrrÚ is_acceptable8s zfind_p_q..is_acceptableF)ÚlogÚdebugÚmaxÚmin) ÚnbitsÚ getprime_funcruÚshiftZpbitsZqbitsrXrYrwZchange_pr)rurvrÚfind_p_q s      rc Csr|d|d}ytjj||ƒ}Wn$tk rFtd||fƒ‚YnX|||dkrjtd|||fƒ‚||fS)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 rSz.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)rXrYÚexponentZphi_nrWrrrÚcalculate_keys_custom_exponentYs r�cCs t||tƒS)zûCalculates 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)rXrYrrrÚcalculate_keysus rƒc CsTxFt|d||ƒ\}}yt|||d�\}}PWqtk rBYqXqW||||fS)aWGenerate 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 rs)r€)rr�r)r|r}rur€rXrYrrWrrrÚgen_keys‚s r„rSc Cs”|dkrtdƒ‚|dkr$td|ƒ‚|dkrRddlm}ddl}|j|j|d�}ntjj}t||||d �\}}} } ||} t| | ƒt | | | ||ƒfS) 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. rtz Key too smallrSzPool size (%i) should be >= 1r)ÚparallelN)Úpoolsize)rur€) rr"r…Ú functoolsÚpartialÚgetprimeÚprimer„r.rV) r|rur†r€r…r‡r}rXrYrrWrrrrÚnewkeysžs  r‹Ú__main__édé z%i timesZAbortedz Doctests done)"r*ÚloggingZ rsa._compatrZ rsa.primer"Zrsa.pemZ rsa.commonZ rsa.randnumZrsa.coreÚ getLoggerr'rxr‚Úobjectrr.rVrŠr‰rr�rƒr„r‹Ú__all__ÚdoctestÚrangeÚcountÚtestmodZfailuresÚtestsÚprintÚKeyboardInterruptrrrrÚ"s@  W eN 5