3 M(YSY @sVdZddlZddlmZddlZddlZddlZddlZddl Zej e Z dZ GdddeZGdddeZGd d d eZejjd fd d ZddZddZd e fddZd de fddZdd dgZe dkrRddlZyPxJedD]>Zej\ZZerPereddksedkre deqWWne!k rHe dYn Xe ddS)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@sPeZdZdZdZddZedddZed d Z dd d Z d dZ ddZ dS) AbstractKeyz0Abstract superclass for private and public keys.necCs||_||_dS)N)rr)selfrrr./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)clskeyfileformatmethodsmethodrrr load_pkcs1:s   zAbstractKey.load_pkcs1c CsDy||Stk r>djt|j}td||fYnXdS)zBChecks whether the given file format exists in 'methods'. z, z%Unsupported format: %r, try one of %sN)KeyErrorjoinsortedkeys ValueError)Z file_formatrformatsrrrrMs z!AbstractKey._assert_format_existscCs |j|jd}|j||}|S)zSaves 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)aPerforms 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)rmessagerrrrblindhszAbstractKey.blindcCstjj||j||jS)aPerforms 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 )rsacommoninverser)rblindedr rrrunblindys zAbstractKey.unblindN)rr)r )r ) __name__ __module__ __qualname____doc__ __slots__r classmethodr staticmethodrrr!r&rrrrr1s  rc@seZdZdZdZddZddZdd Zd d Zd d Z ddZ e ddZ ddZ e ddZddZe ddZe ddZdS) PublicKeyaRepresents 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)rkeyrrr __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)rstaterrr __setstate__szPublicKey.__setstate__cCs2|dkr dSt|tsdS|j|jko0|j|jkS)NF) isinstancer.rr)rotherrrr__eq__s  zPublicKey.__eq__cCs ||k S)Nr)rr7rrr__ne__szPublicKey.__ne__cCsHddlm}ddlm}|j||d\}}|t|dt|ddS)aLoads 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)asn1SpecmoduluspublicExponent)rr)pyasn1.codec.derr:rsa.asn1r;decodeint)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;setComponentByNamerrencode)rrEr;asn_keyrrrrs   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"pemload_pemr )rrderrrrr s zPublicKey._load_pkcs1_pemcCs|j}tjj|dS)zSaves a PKCS#1 PEM-encoded public key file. :return: contents of a PEM-encoded file that contains the public key. zRSA PUBLIC KEY)rr"rIsave_pem)rrKrrrrszPublicKey._save_pkcs1_pemcCstjj|d}|j|S)aLoads 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"rIrJload_pkcs1_openssl_der)rrrKrrrload_pkcs1_openssl_pemsz PublicKey.load_pkcs1_openssl_pemcCslddlm}ddlm}ddlm}|j||d\}}|dd|jdkrVtd |j |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) OpenSSLPubKey)r:)univ)r<headeroidz1.2.840.113549.1.1.1z7This is not a DER-encoded OpenSSL-compatible public keyr0N) 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@seZdZdZd%Zd&d d Zd dZddZddZddZ ddZ ddZ ddZ ddZ eddZdd 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 rrdpqexp1exp2coefNc Cstj|||||_||_||_|dkrtjj|jd}|j||}tjj||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 rS) r"randnumrandintrr!coreZ decrypt_intrWr&)r encryptedblind_rr%Z decryptedrrrblinded_decrypts  zPrivateKey.blinded_decryptcCs>tjj|jd}|j||}tjj||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 rS) r"r]r^rr!r_Z encrypt_intrWr&)rrrar%r`rrrblinded_encrypts  zPrivateKey.blinded_encryptcCsXddlm}|j|\}}|ddkr6td|dtdd|ddD}||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).0xrrr sz-PrivateKey._load_pkcs1_der..rS )r?r:rArtuple)rrr:rCrDZas_intsrrrr s   zPrivateKey._load_pkcs1_dercsddlmmddlm}Gfdddj}|}|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 seZdZjjdjjdjjdjjdjjdjjdjjdjjdjjd j Zd S) z.PrivateKey._save_pkcs1_der..AsnPrivKeyversionr=r>privateExponentprime1prime2 exponent1 exponent2 coefficientN)r'r(r)Z NamedTypesZ NamedTypeZIntegerZ componentTyper)rirPrr AsnPrivKeysrqrjr=r>rkrlrmrnrorp)rTrPrir?rESequencerFrrrWrXrYrZr[r\rG)rrErqrHr)rirPrrs  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|tdS)zSaves 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 dSsdStjj||}|kS)zReturns 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)logdebugmaxmin) nbits getprime_funcrushiftZpbitsZqbitsrXrYrwZchange_pr)rurvrfind_p_q s      rc Csr|d|d}ytjj||}Wn$tk rFtd||fYnX|||dkrjtd|||f||fS)aCalculates 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)rXrYexponentZphi_nrWrrrcalculate_keys_custom_exponentYs rcCs t||tS)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. )rDEFAULT_EXPONENT)rXrYrrrcalculate_keysus rc 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)rrr)r|r}rurrXrYrrWrrrgen_keyss rrSc Cs|dkrtd|dkr$td||dkrRddlm}ddl}|j|j|d}ntjj}t||||d \}}} } ||} t| | t | | | ||fS) aGenerates 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 functoolspartialgetprimeprimerr.rV) r|rurrrrr}rXrYrrWrrrrnewkeyss  r__main__d z%i timesZAbortedz Doctests done)"r*loggingZ rsa._compatrZ rsa.primer"Zrsa.pemZ rsa.commonZ rsa.randnumZrsa.core getLoggerr'rxrobjectrr.rVrrrrrrr__all__doctestrangecounttestmodZfailurestestsprintKeyboardInterruptrrrr"s@  W eN 5