o ak@sdZddlZddlZddlZddlZddlZddlZddlZddl Zddl Ze e Z dZGdddZGdddeZGdd d eZejjd fd ed ejegefd edejeeffddZdedededejeeffddZdededejeeffddZd efd ed ejegefd ededejeeeeff ddZd defd ed edededejeeff ddZgdZe dkrddlZz%ed D]Z e!\Z"Z#e"rne d!dkre se dkre$d"e qWne%ye$d#YdSwe$d$dSdS)%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"eZdZdZdZdededdfddZed eddfd d Z ed eddfd d Z defddZ defddZ ed'd ede ddfddZede deje ejfdejfddZd'de defddZdedejeeffddZded edefd!d"Zdefd#d$Zdejeeffd%d&ZdS)( AbstractKeyz0Abstract superclass for private and public keys.)neblindfacblindfac_inversemutexrrreturnNcCs&||_||_d|_|_t|_dS)N)rrrr threadingLockr)selfrrr )/usr/lib/python3/dist-packages/rsa/key.py__init__7s zAbstractKey.__init__keyfilecCdS)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_pemBzAbstractKey._load_pkcs1_pemcCr)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 rr r r_load_pkcs1_derNrzAbstractKey._load_pkcs1_dercCr)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_pemZrzAbstractKey._save_pkcs1_pemcCr)zSaves the key in PKCS#1 DER format, implement in a subclass. :returns: the DER-encoded key. :rtype: bytes Nr rr r r_save_pkcs1_derarzAbstractKey._save_pkcs1_derPEMformatcCs"|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_formatrc CsHz||WSty#}zdt|}td||f|d}~ww)z9Checks whether the given file format exists in 'methods'.z, z%Unsupported format: %r, try one of %sN)KeyErrorjoinsortedkeys ValueError)r"rexformatsr r rr~s  z!AbstractKey._assert_format_existscCs |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 r)rrr)r rrr r r r save_pkcs1s   zAbstractKey.save_pkcs1messagecCs.|\}}|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.blindr.rcCs|||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.unblindcCs@tdD]}tj|jd}tj|j|r|Sqtd)Nizunable to find blinding factor)rangersarandnumrandintrprimeare_relatively_prime RuntimeError)r _blind_rr r r_initial_blinding_factors z$AbstractKey._initial_blinding_factorcCs|j5|jdkr||_tj|j|j|_nt|jd|j|_t|jd|j|_|j|jfWdS1s;wYdS)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) rrr;r3commoninverserrr-rr r rr,s   $z#AbstractKey._update_blinding_factor)r)__name__ __module__ __qualname____doc__ __slots__intr classmethodbytesrrrrstrr! staticmethodtypingMappingCallablerr*Tupler/r0r;r,r r r rr2s2      rc@seZdZdZdZdedefddZdefddZde j eeffd d Z d e j eefdd fd dZ de j defddZde j defddZdefddZededdfddZdefddZededdfddZdefddZededdfdd Zededdfd!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 rrkeyrcC t||SNgetattrr rOr r r __getitem__ zPublicKey.__getitem__cCsd|j|jfS)NzPublicKey(%i, %i)rNrr r r__repr__zPublicKey.__repr__cCs |j|jfSz&Returns the key as tuple for pickling.rNrr r r __getstate__s zPublicKey.__getstate__stateNcCs"|\|_|_t||j|jdSzSets the key from tuple.N)rrrrr r[r r r __setstate__s zPublicKey.__setstate__othercCs2|durdSt|ts dS|j|jko|j|jkSNF) isinstancerMrrr r_r r r__eq__s  zPublicKey.__eq__cC ||k SrQr rbr r r__ne__ rVzPublicKey.__ne__cCst|j|jfSrQ)hashrrrr r r__hash__rXzPublicKey.__hash__rcCsHddlm}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) rdecoder AsnPubKeyasn1SpecmoduluspublicExponentrN)pyasn1.codec.derrirsa.asn1rkdecoderD)rrrirkprivr9r 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 rencoderrjrnro)rprurqrksetComponentByNamerrencode)r rurkasn_keyr r rr,s   zPublicKey._save_pkcs1_dercCtj|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 RSA PUBLIC KEYr3pemload_pemrrrderr r rr=s zPublicKey._load_pkcs1_pemcC|}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 rzrr3r|save_pemr rr r rrLzPublicKey._save_pkcs1_pemcCry)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)r3r|r}load_pkcs1_openssl_derr~r r rload_pkcs1_openssl_pemVs z PublicKey.load_pkcs1_openssl_pemcCslddlm}ddlm}ddlm}|j||d\}}|dd|dkr+td | |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) OpenSSLPubKeyrh)univrlheaderoidz1.2.840.113549.1.1.1z7This is not a DER-encoded OpenSSL-compatible public keyrOr1N) rqrrpri pyasn1.typerrrObjectIdentifier TypeErrorr)rrrrirkeyinfor9r r rris  z PublicKey.load_pkcs1_openssl_der)r?r@rArBrCrGrDrUrWrIrLrZr^AnyboolrcrergrErFrrrrrrr r r rrMs(  rMc @sDeZdZdZdZdedededededd f d d Zd edefd dZdefddZ de j eeeeeeeeffddZ de j eeeeeeeefdd fddZ de jdefddZde jdefddZdefddZdedefddZd edefd!d"Zed#eddfd$d%Zdefd&d'Zed#eddfd(d)Zdefd*d+Zd S), 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 rrdpqexp1exp2coefrrrrrrNcCsXt|||||_||_||_t||d|_t||d|_tj |||_ dS)Nr1) rrrrrrDrrr3r=r>r)r rrrrrr r rrszPrivateKey.__init__rOcCrPrQrRrTr r rrUrVzPrivateKey.__getitem__cCsd|j|j|j|j|jfS)NzPrivateKey(%i, %i, %i, %i, %i))rrrrrrr r rrWszPrivateKey.__repr__cCs$|j|j|j|j|j|j|j|jfSrYrrr r rrZs$zPrivateKey.__getstate__r[c Cs:|\|_|_|_|_|_|_|_|_t ||j|jdSr\) rrrrrrrrrrr]r r rr^s$zPrivateKey.__setstate__r_cCsz|durdSt|ts dS|j|jko<|j|jko<|j|jko<|j|jko<|j|jko<|j|jko<|j|jko<|j |j kSr`) rarrrrrrrrrrbr r rrcs&         zPrivateKey.__eq__cCrdrQr rbr r rrerVzPrivateKey.__ne__c Cs(t|j|j|j|j|j|j|j|jfSrQ) rfrrrrrrrrrr r rrgs(zPrivateKey.__hash__ encryptedcCs\||\}}t||j|j}t||j|j}|||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 )r/r-rrrrrr0)r rr.rs1s2h decryptedr r rblinded_decrypts   zPrivateKey.blinded_decryptr+cCs.||\}}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/r3core encrypt_intrrr0)r r+r.rrr r rblinded_encrypts  zPrivateKey.blinded_encryptrc Csddlm}||\}}|ddkrtd|dtt|dd}||}tt|dd\}}} |j|j|jf||| fkrGt 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) rrhz)Unable to read this file, version %s != 0r1 zYou have provided a malformed keyfile. Either the exponents or the coefficient are incorrect. Using the correct values instead.) rprirrr'maprDrrrwarningswarn UserWarning) rrrirsr9as_intsrOrrrr 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)r namedtypertcseZdZddddddddd  Zd S) z.PrivateKey._save_pkcs1_der..AsnPrivKeyversionrnroprivateExponentprime1prime2 exponent1 exponent2 coefficientN)r?r@rA NamedTypes NamedTypeInteger componentTyper rrr r AsnPrivKey;srrrnrorrrrrr)rrrrpruSequencervrrrrrrrrrw)r rurrxr rrr1s   zPrivateKey._save_pkcs1_dercCry)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 RSA PRIVATE KEYr{r~r r rrVs zPrivateKey._load_pkcs1_pemcCr)zSaves a PKCS#1 PEM-encoded private key file. :return: contents of a PEM-encoded file that contains the private key. :rtype: bytes rrrr r rrfrzPrivateKey._save_pkcs1_pem)r?r@rArBrCrDrrGrUrWrIrLrZr^rrrcrergrrrErFrrrrr r r rr~s&" $ (:%rTnbits getprime_funcaccuraterc s|d|d}||}||}td|||}td|||}dtdtdtffdd }d } |||sL| r@||}n||}| } |||r9t||t||fS) a&Returns a tuple of two different primes of nbits bits each. The resulting p * q has exactly 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 r<zfind_p_q(%i): Finding pzfind_p_q(%i): Finding qrrrcs,||krdSs dStj||}|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)r3r=bit_size)rr found_sizer total_bitsr r is_acceptables zfind_p_q..is_acceptableF)logdebugrDrmaxmin) rrrshiftpbitsqbitsrrrchange_pr rrfind_p_qqs"#      rrrexponentc Cs|d|d}z tj||}Wn tjjy1}ztjj|||jd|||jfd|d}~ww|||dkrCtd|||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 r1z;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))r3r=r>NotRelativePrimeErrorrr')rrrphi_nrr(r r rcalculate_keys_custom_exponents*    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)rrr r rcalculate_keyss rcCsN t|d||\}}z t|||d\}}Wn tyYnwq||||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 Tr<)r)rrr')rrrrrrrrr r rgen_keyss  rr1poolsizec s|dkrtddkrtddkr)ddlmdtdtffd 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. rz Key too smallr1zPool size (%i) should be >= 1r)parallelrrcsj|dS)N)r)getprime)rrrr rr<sznewkeys..getprime_func)rr) r'r3rrDr6rrrMr) rrrrrrrrrrr rrnewkeyss  r)rMrr__main__d z%i timesAbortedz Doctests done)&rBloggingr rIr rsa.primer3rsa.pem rsa.common rsa.randnumrsa.core getLoggerr?rrrrMrr6rrDrKrrLrrrrr__all__doctestr2counttestmodfailurestestsprintKeyboardInterruptr r r rs (&v  $R " #  8