B dXj @sdZddlZddlZddlZddlZddlZddlZddlZddl Zddl Ze e Z dZGdddZGdddeZGdd d eZejjd feejegefeejeefd d d ZeeeejeefdddZeeejeefdddZd efeejegefeeejeeeefdddZd defeeeeejeefdddZdd dgZe dkrddlZyVxPedD]DZ e!\Z"Z#e"rPe ddkre se dkr|e$de q|WWne%k re$dYn 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. Nic@s eZdZdZdZeeddddZeedddd Z eeddd d Z ed d dZ ed ddZ ed%ee ddddZee eje ejfejdddZd&e edddZeejeefdddZeeeddd Zed d!d"Zejeefd d#d$ZdS)' AbstractKeyz0Abstract superclass for private and public keys.)neblindfacblindfac_inversemutexN)rrreturncCs&||_||_d|_|_t|_dS)N)rrrr threadingLockr)selfrrr ./tmp/pip-target-jj3kjtpb/lib/python/rsa/key.py__init__7s zAbstractKey.__init__)keyfilercCsdS)zLoads a key in PKCS#1 PEM format, implement in a subclass. :param keyfile: contents of a PEM-encoded file that contains the public key. :type keyfile: bytes :return: the loaded key :rtype: AbstractKey Nr )clsrr r r_load_pkcs1_pemBs zAbstractKey._load_pkcs1_pemcCsdS)zLoads a key in PKCS#1 PEM format, implement in a subclass. :param keyfile: contents of a DER-encoded file that contains the public key. :type keyfile: bytes :return: the loaded key :rtype: AbstractKey Nr )rrr r r_load_pkcs1_derNs zAbstractKey._load_pkcs1_der)rcCsdS)zSaves the key in PKCS#1 PEM format, implement in a subclass. :returns: the PEM-encoded key. :rtype: bytes Nr )r r r r_save_pkcs1_pemZszAbstractKey._save_pkcs1_pemcCsdS)zSaves the key in PKCS#1 DER format, implement in a subclass. :returns: the DER-encoded key. :rtype: bytes Nr )r r r r_save_pkcs1_deraszAbstractKey._save_pkcs1_derPEM)rformatrcCs"|j|jd}|||}||S)aNLoads a key in PKCS#1 DER or PEM format. :param keyfile: contents of a DER- or PEM-encoded file that contains the key. :type keyfile: bytes :param format: the format of the file to load; 'PEM' or 'DER' :type format: str :return: the loaded key :rtype: AbstractKey )rDER)rr_assert_format_exists)rrrmethodsmethodr r r load_pkcs1hs  zAbstractKey.load_pkcs1) file_formatrrcCsDy||Stk r>dt|}td||fYnXdS)zBChecks whether the given file format exists in 'methods'. z, z%Unsupported format: %r, try one of %sN)KeyErrorjoinsortedkeys ValueError)rrformatsr r rr~s z!AbstractKey._assert_format_exists)rrcCs |j|jd}|||}|S)zSaves the key in PKCS#1 DER or PEM format. :param format: the format to save; 'PEM' or 'DER' :type format: str :returns: the DER- or PEM-encoded key. :rtype: bytes )rr)rrr)r rrrr r r save_pkcs1s   zAbstractKey.save_pkcs1)messagercCs.|\}}|t||j|j|j}||fS)aPerforms blinding on the message. :param message: the message, as integer, to blind. :param r: the random number to blind with. :return: tuple (the blinded message, the inverse of the used blinding factor) The blinding is such that message = unblind(decrypt(blind(encrypt(message))). See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29 )_update_blinding_factorpowrr)r r%rrblindedr r rblinds zAbstractKey.blind)r(rrcCs|||jS)aPerforms blinding on the message using random number 'blindfac_inverse'. :param blinded: the blinded message, as integer, to unblind. :param blindfac: the factor 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 )r)r r(rr r runblinds zAbstractKey.unblindcCsDx6tdD]*}tj|jd}tj|j|r |Sq WtddS)Nizunable to find blinding factor)rangersaZrandnumrandintrprimeZare_relatively_prime RuntimeError)r _Zblind_rr r r_initial_blinding_factors z$AbstractKey._initial_blinding_factorc Csl|j\|jdkr2||_tj|j|j|_n$t|jd|j|_t|jd|j|_|j|jfSQRXdS)aUpdate blinding factors. Computing a blinding factor is expensive, so instead this function does this once, then updates the blinding factor as per section 9 of 'A Timing Attack against RSA with the Chinese Remainder Theorem' by Werner Schindler. See https://tls.mbed.org/public/WSchindler-RSA_Timing_Attack.pdf :return: the new blinding factor and its inverse. rN) rrr2r-commoninverserrr')r r r rr&s   z#AbstractKey._update_blinding_factor)r)r)__name__ __module__ __qualname____doc__ __slots__intr classmethodbytesrrrrstrr staticmethodtypingMappingCallablerr$Tupler)r*r2r&r r r rr2s&     rc@seZdZdZdZeedddZedddZe j eefdd d Z e j eefd d d dZ e j edddZe j edddZedddZeeddddZedddZeeddddZedddZeedddd Zeeddd!d"Zd S)# 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 access 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 )rr)keyrcCs t||S)N)getattr)r rEr r r __getitem__szPublicKey.__getitem__)rcCsd|j|jfS)NzPublicKey(%i, %i))rr)r r r r__repr__szPublicKey.__repr__cCs |j|jfS)z&Returns the key as tuple for pickling.)rr)r r r r __getstate__szPublicKey.__getstate__N)statercCs"|\|_|_t||j|jdS)zSets the key from tuple.N)rrrr)r rJr r r __setstate__s zPublicKey.__setstate__)otherrcCs2|dkr dSt|tsdS|j|jko0|j|jkS)NF) isinstancerDrr)r rLr r r__eq__s  zPublicKey.__eq__cCs ||k S)Nr )r rLr r r__ne__ szPublicKey.__ne__cCst|j|jfS)N)hashrr)r r r r__hash__ szPublicKey.__hash__)rrcCsHddlm}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.derrRrsa.asn1rSdecoder;)rrrRrSprivr1r r rrs  zPublicKey._load_pkcs1_dercCsDddlm}ddlm}|}|d|j|d|j||S)zxSaves the public key in PKCS#1 DER format. :returns: the DER-encoded public key. :rtype: bytes r)encoder)rSrUrV)rWr[rXrSsetComponentByNamerrencode)r r[rSasn_keyr r rr*s   zPublicKey._save_pkcs1_dercCstj|d}||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)rrderr r rr;s zPublicKey._load_pkcs1_pemcCs|}tj|dS)zSaves a PKCS#1 PEM-encoded public key file. :return: contents of a PEM-encoded file that contains the public key. :rtype: bytes zRSA PUBLIC KEY)rr-r_save_pem)r rar r rrJszPublicKey._save_pkcs1_pemcCstj|d}||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. :type keyfile: bytes :return: a PublicKey object z PUBLIC KEY)r-r_r`load_pkcs1_openssl_der)rrrar r rload_pkcs1_openssl_pemTsz PublicKey.load_pkcs1_openssl_pemcCslddlm}ddlm}ddlm}|j||d\}}|dd|dkrVtd | |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)rR)univ)rTheaderoidz1.2.840.113549.1.1.1z7This is not a DER-encoded OpenSSL-compatible public keyrEr+N) rXrerWrR pyasn1.typerfrYZObjectIdentifier TypeErrorr)rrrerRrfZkeyinfor1r r rrcgs   z PublicKey.load_pkcs1_openssl_der)r6r7r8r9r:r>r;rGrHr@rCrIrKAnyboolrNrOrQr<r=rrrrrdrcr r r rrDs&  rDc @s*eZdZdZdZeeeeeddddZeeddd Zed d d Z e j eeeeeeeefd d dZ e j eeeeeeeefddddZ e jedddZe jedddZed ddZeedddZeedddZeeddd d!Zed d"d#Zeeddd$d%Zed d&d'ZdS)( PrivateKeyaRepresents 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 access is faster, though. >>> PrivateKey(3247, 65537, 833, 191, 17) PrivateKey(3247, 65537, 833, 191, 17) exp1, exp2 and coef will be calculated: >>> pk = PrivateKey(3727264081, 65537, 3349121513, 65063, 57287) >>> pk.exp1 55063 >>> pk.exp2 10095 >>> pk.coef 50797 )rrdpqexp1exp2coefN)rrrnrorprcCsXt|||||_||_||_t||d|_t||d|_tj |||_ dS)Nr+) rrrnrorpr;rqrrr-r4r5rs)r rrrnrorpr r rrszPrivateKey.__init__)rErcCs t||S)N)rF)r rEr r rrGszPrivateKey.__getitem__)rcCsd|j|j|j|j|jfS)NzPrivateKey(%i, %i, %i, %i, %i))rrrnrorp)r r r rrHszPrivateKey.__repr__cCs$|j|j|j|j|j|j|j|jfS)z&Returns the key as tuple for pickling.)rrrnrorprqrrrs)r r r rrIszPrivateKey.__getstate__)rJrc Cs:|\|_|_|_|_|_|_|_|_t ||j|jdS)zSets the key from tuple.N) rrrnrorprqrrrsrr)r rJr r rrKs$zPrivateKey.__setstate__)rLrcCsz|dkr dSt|tsdS|j|jkox|j|jkox|j|jkox|j|jkox|j|jkox|j|jkox|j|jkox|j |j kS)NF) rMrmrrrnrorprqrrrs)r rLr r rrNs        zPrivateKey.__eq__cCs ||k S)Nr )r rLr r rrOszPrivateKey.__ne__c Cs(t|j|j|j|j|j|j|j|jfS)N) rPrrrnrorprqrrrs)r r r rrQszPrivateKey.__hash__) encryptedrcCs.||\}}tj||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 )r)r-coreZ decrypt_intrnrr*)r rtr(rZ decryptedr r rblinded_decrypts zPrivateKey.blinded_decrypt)r%rcCs.||\}}tj||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 )r)r-ruZ encrypt_intrnrr*)r r%r(rrtr r rblinded_encrypts zPrivateKey.blinded_encrypt)rrc Csddlm}||\}}|ddkr6td|dtt|dd}||}tt|dd\}}} |j|j|jf||| fkrt dt |S)a4Loads a key in PKCS#1 DER format. :param keyfile: contents of a DER-encoded file that contains the private key. :type keyfile: bytes :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)rRz)Unable to read this file, version %s != 0r+ zYou have provided a malformed keyfile. Either the exponents or the coefficient are incorrect. Using the correct values instead.) rWrRrYr"mapr;rqrrrswarningswarn UserWarning) rrrRrZr1Zas_intsrErqrrrsr r rrs  zPrivateKey._load_pkcs1_dercsddlmmddlm}Gfdddj}|}|dd|d|j|d|j|d |j |d |j |d |j |d |j |d |j |d|j||S)zzSaves the private key in PKCS#1 DER format. :returns: the DER-encoded private key. :rtype: bytes r)rf namedtype)r[cseZdZddddddddd  Zd S) z.PrivateKey._save_pkcs1_der..AsnPrivKeyversionrUrVprivateExponentprime1prime2 exponent1 exponent2 coefficientN)r6r7r8Z NamedTypesZ NamedTypeIntegerZ componentTyper )r~rfr r AsnPrivKey'srrrUrVrrrrrr)rirfr~rWr[Sequencer\rrrnrorprqrrrsr])r r[rr^r )r~rfrrs  zPrivateKey._save_pkcs1_dercCstj|d}||S)aqLoads 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. :type keyfile: bytes :return: a PrivateKey object sRSA PRIVATE KEY)r-r_r`r)rrrar r rrBs zPrivateKey._load_pkcs1_pemcCs|}tj|dS)zSaves a PKCS#1 PEM-encoded private key file. :return: contents of a PEM-encoded file that contains the private key. :rtype: bytes sRSA PRIVATE KEY)rr-r_rb)r rar r rrRszPrivateKey._save_pkcs1_pem)r6r7r8r9r:r;rr>rGrHr@rCrIrKrkrlrNrOrQrvrwr<r=rrrrr r r rrm|s$ $&9%rmT)nbits getprime_funcaccuraterc s|d|d}||}||}td|||}td|||}tttdfdd }d} x*|||s| r~||}n||}| } qfWt||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 r3zfind_p_q(%i): Finding pzfind_p_q(%i): Finding q)rorprcs,||kr dSsdStj||}|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-r4Zbit_size)rorpZ found_size)r total_bitsr r is_acceptables zfind_p_q..is_acceptableF)logdebugr;rlmaxmin) rrrshiftZpbitsZqbitsrorprZchange_pr )rrrfind_p_q]s !     r)rorpexponentrc Cs|d|d}ytj||}WnHtjjk rj}z&tjj|||jd|||jfdWdd}~XYnX|||dkrtd|||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 r+z;e (%d) and phi_n (%d) are not relatively prime (divider=%i))msgNz6e (%d) and d (%d) are not mult. inv. modulo phi_n (%d))r-r4r5ZNotRelativePrimeErrorrnr")rorprZphi_nrnexr r rcalculate_keys_custom_exponents $r)rorprcCs 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)rorpr r rcalculate_keyss r)rrrrrcCsTxFt|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 r3)r)rrr")rrrrrorprrnr r rgen_keyss rr+)rrpoolsizerrc s|dkrtddkr$tddkrPddlmttdfdd }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. rz Key too smallr+zPool size (%i) should be >= 1r)parallel)rrcsj|dS)N)r)getprime)r)rrr rrsznewkeys..getprime_func)rr) r"r-rr;r/rrrDrm) rrrrrrorprrnrr )rrrnewkeyss  r__main__d z%i timesZAbortedz Doctests done)&r9loggingr r@r{Z rsa.primer-Zrsa.pemZ rsa.commonZ rsa.randnumZrsa.core getLoggerr6rrrrDrmr/rr;rBrlrCrrrrr__all__doctestr,counttestmodZfailurestestsprintKeyboardInterruptr r r r sN &&c.N4$5