;i#kdZddlZddlZddlZddlZddlZddlZddlZddl ZdZ ej ddZ GddZ Gdd e ZGd d e Zejjd fd edejegefdedejeeffdZdedededejeeffdZdededejeeffdZd e fd edejegefdededejeeeeff dZd de fd ededededejeeff dZgdZedkrlddlZ edD]7Zej \Z!Z"e!rn edzdkresedkre#dez8e#d dS#e$$re#d!YdSwxYwdS)"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. NiT AbstractKey)boundc eZdZdZdZdededdfdZedej e d e de fd Z edej e d e de fd Z de fd Zde fd Zeddej e d e dede fdZededejeejfdejfdZddede fdZdedejeeffdZdededefdZdefdZdejeeffdZdS)rz0Abstract superclass for private and public keys.)neblindfacblindfac_inversemutexrrreturnNcn||_||_dx|_|_t j|_dS)N)rrr r threadingLockr )selfrrs ;C:\PYTHON\MyICR_Workspace\venv\Lib\site-packages\rsa/key.py__init__zAbstractKey.__init__8s6132 -^%% clskeyfilecdS)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 Nrrs r_load_pkcs1_pemzAbstractKey._load_pkcs1_pemCrcdS)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 Nrrs r_load_pkcs1_derzAbstractKey._load_pkcs1_derOrrcdS)zSaves the key in PKCS#1 PEM format, implement in a subclass. :returns: the PEM-encoded key. :rtype: bytes Nrrs r_save_pkcs1_pemzAbstractKey._save_pkcs1_pem[rrcdS)zSaves the key in PKCS#1 DER format, implement in a subclass. :returns: the DER-encoded key. :rtype: bytes Nrrs r_save_pkcs1_derzAbstractKey._save_pkcs1_derbrrPEMformatcb|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 r#DER)rr_assert_format_exists)rrr$methodsmethods r load_pkcs1zAbstractKey.load_pkcs1isA&&   **67;;vgr file_formatr)c ||S#t$rO}dt|}t d|d||d}~wwxYw)z9Checks whether the given file format exists in 'methods'.z, zUnsupported format: z , try one of N)KeyErrorjoinsortedkeys ValueError)r,r)exformatss rr(z!AbstractKey._assert_format_existssw  ;' '   iiw||~~ 6 677G*;F;;P  s A#A AA#c`|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&)r r"r()rr$r)r*s r save_pkcs1zAbstractKey.save_pkcs1s>''   ++FG<<vxxrmessagec|\}}|t||j|jz|jz}||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)rr7r r blindeds rblindzAbstractKey.blindsH&*%A%A%C%C""S4646:::dfD(((rr;r c||z|jzS)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)rr;r s runblindzAbstractKey.unblinds!7*df44rctdD]R}tj|jdz }tj|j|r|cSStd)Nizunable to find blinding factor)rangersarandnumrandintrprimeare_relatively_prime RuntimeError)r_blind_rs r_initial_blinding_factorz$AbstractKey._initial_blinding_factorskt  Ak))$&1*55Gy--dfg>>  ;<<B;)r#)__name__ __module__ __qualname____doc__ __slots__intr classmethodtypingTyperbytesrrr r"strr+ staticmethodMappingCallabler(r6Tupler<r>rJr9rrrrr3sB::CI &# &# &$ & & & &  V[^  e      [    V[^  e      [             APQ[*  #)>#v2F#G     \ " )S )V\#s(%; ) ) ) ) 5s 5c 5c 5 5 5 5=#====8c3h)?888888rcZeZdZdZdZdedefdZdefdZde j eeffdZ de j eefdd fd Z d e j defd Zd e j defd ZdefdZededdfdZdefdZededdfdZdefdZededdfdZededdfdZd 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 rkeyr c"t||SNgetattrrr`s r __getitem__zPublicKey.__getitem__tS!!!rc$d|j|jfzS)NzPublicKey(%i, %i)rrrs r__repr__zPublicKey.__repr__s"dfdf%555rc|j|jfSz&Returns the key as tuple for pickling.rirs r __getstate__zPublicKey.__getstate__svtv~rstateNcp|\|_|_t||j|jdSzSets the key from tuple.N)rrrrrrns r __setstate__zPublicKey.__setstate__s1T464622222rothercx|dSt|tsdS|j|jko|j|jkSNF) isinstancer_rrrrss r__eq__zPublicKey.__eq__s@ =5%++ 5v 6TVuw%66rc||k Srbrrws r__ne__zPublicKey.__ne__ EM""rc8t|j|jfSrb)hashrrrs r__hash__zPublicKey.__hash__sTVTV$%%%rrcddlm}ddlm}|||\}}|t |dt |dS)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 AsnPubKeyasn1SpecmoduluspublicExponentri)pyasn1.codec.derrrsa.asn1rdecoderT)rrrrprivrHs rrzPublicKey._load_pkcs1_dersv* -,,,,,&&&&&&NN7YY[[NAA qsSi))S6F1G-H-HIIIIrcddlm}ddlm}|}|d|j|d|j||S)zxSaves the public key in PKCS#1 DER format. :returns: the DER-encoded public key. :rtype: bytes rencoderrrr)rrrrsetComponentByNamerrencode)rrrasn_keys rr"zPublicKey._save_pkcs1_der-sx -,,,,,&&&&&&)++""9df555""#3TV<<<~~g&&&rcltj|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 KEYrBpemload_pemrrrders rrzPublicKey._load_pkcs1_pem>s0gw(899""3'''rcj|}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 rr"rBrsave_pemrrs rr zPublicKey._save_pkcs1_pemMs.""$$w%5666rcltj|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)rBrrload_pkcs1_openssl_derrs rload_pkcs1_openssl_pemz PublicKey.load_pkcs1_openssl_pemWs/ gw 55))#...rcddlm}ddlm}ddlm}|||\}}|dd|dkrtd | |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) OpenSSLPubKeyr)univrheaderoidz1.2.840.113549.1.1.1z7This is not a DER-encoded OpenSSL-compatible public keyr`r@N) rrrr pyasn1.typerrObjectIdentifier TypeErrorr)rrrrrkeyinforHs rrz PublicKey.load_pkcs1_openssl_derjs +*****,,,,,,$$$$$$~~g ~HH ! 8 U #t'<'<=S'T'T T TUVV V""75>!""#5666r)rOrPrQrRrSrYrTrfrjrVr]rmrrAnyboolrxrzr~rUrXrr"rr rrrrrr_r_s .I"s"s""""6#6666fl3843&,sCx"83T3333 7FJ747777#FJ#4####&#&&&&JeJ JJJ[J4'''''" (e ( ( ( ([ (77777/U/{///[/$7U7{777[777rr_c reZdZdZdZdedededededd f d Zd edefd Zdefd Z de j eeeeeeeeffdZ de j eeeeeeeefdd fdZ de jdefdZde jdefdZdefdZdedefdZdedefdZededdfdZdefdZededdfdZdefdZd 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 )dpqexp1exp2coefrrrrrr Nct|||||_||_||_t ||dz z|_t ||dz z|_tj |||_ dS)Nr@) rrrrrrTrrrBrMrNr)rrrrrrs rrzPrivateKey.__init__s|T1a(((QU $$ QU $$ J&&q!,, rr`c"t||Srbrcres rrfzPrivateKey.__getitem__rgrcHd|j|j|j|j|jfzS)NzPrivateKey(%i, %i, %i, %i, %i))rrrrrrs rrjzPrivateKey.__repr__s-/ F F F F F 3   rcf|j|j|j|j|j|j|j|jfSrl)rrrrrrrrrs rrmzPrivateKey.__getstate__s)vtvtvtvtvty$)TYVVrrnc |\|_|_|_|_|_|_|_|_t ||j|jdSrp) rrrrrrrrrrrqs rrrzPrivateKey.__setstate__sJRWO 49diT464622222rrsc8|dSt|tsdS|j|jkoo|j|jko_|j|jkoO|j|jko?|j|jko/|j|jko|j|jko|j |j kSru) rvrrrrrrrrrrws rrxzPrivateKey.__eq__s =5%,, 5 Feg  (%'! (%'! (%'! (%'!  (  UZ'  (  UZ'  ( UZ' rc||k Srbrrws rrzzPrivateKey.__ne__r{rc t|j|j|j|j|j|j|j|jfSrb) r}rrrrrrrrrs rr~zPrivateKey.__hash__s3TVTVTVTVTVTY SWS\]^^^r encryptedc||\}}t||j|j}t||j|j}||z |jz|jz}||j|zz}|||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:rrrrrr>)rrr;r s1s2h decrypteds rblinded_decryptzPrivateKey.blinded_decrypts%)JJy$9$9!! $)TV , , $)TV , ,2g "df ,!O ||I'7888rr7c||\}}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<rBcore encrypt_intrrr>)rr7r;r rs rblinded_encryptzPrivateKey.blinded_encryptsM%)JJw$7$7!!H(($&$&AA ||I'7888rrczddlm}||\}}|ddkrtd|dzt t |dd}||}t t |dd\}}} |j|j|jf||| fkrtj 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) 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.) rrrr2maprTrrrwarningswarn UserWarning) rrrrrHas_intsr`rrrs rrzPrivateKey._load_pkcs1_ders, -,,,,,NN7++ q" 7a<<H4PQ7RSS Sc4!9%%c7msD1I..dD Hch )dD$-? ? ? M     rchddlmmddlm}Gfddj}|}|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 namedtyperceZdZddddddddd  Zd S) .PrivateKey._save_pkcs1_der..AsnPrivKeyversionrrprivateExponentprime1prime2 exponent1 exponent2 coefficientN)rOrPrQ NamedTypes NamedTypeInteger componentType)rrsr AsnPrivKeyr<s%00##It||~~>>##It||~~>>##$4dllnnEE##$5t||~~FF##Hdllnn==##Hdllnn==##K@@##K@@##M4<<>>BB  MMMrrrrrrrrrrr)rrrrrSequencerrrrrrrrrr)rrrrrrs @@rr"zPrivateKey._save_pkcs1_der2sb 0///////,,,,,,           *,,""9a000""9df555""#3TV<<<""#4df===""8TV444""8TV444""; :::""; :::""=$)<<<~~g&&&rcltj|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 RSA PRIVATE KEYrrs rrzPrivateKey._load_pkcs1_pemWs0gw(:;;""3'''rcj|}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 rrrs rr zPrivateKey._save_pkcs1_pemgs.""$$w%7888r)rOrPrQrRrSrTrrYrfrjrVr]rmrrrrrxrzr~rrrUrXrr"rr rrrrrsT.8I -# -# -# -# -# -$ - - - -"s"s"""" #    Wfl3S#sCc+QRWWWW3&,sCc3SRU/U"V3[_3333  FJ 4    $#FJ#4####_#____9999990 9s 9s 9 9 9 98e8 888[8t#'#'#'#'#'J (e ( ( ( ([ (9999999rrTnbits getprime_funcaccurater c> |dz |dz}||z}||z }||}||}dtdtdtf fd }d} |||s(| r ||}n ||}| } |||(t||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 rLrrr cl||krdSsdStj||z}|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)rBrMbit_size)rr found_sizer total_bitss r is_acceptablezfind_p_q..is_acceptablesF 665 4Z((Q// Z''rF)rTrmaxmin) rrrshiftpbitsqbitsrrrchange_prs ` @rfind_p_qrrsFJ RKE EME EME  eA eA(((((((((($HmAq!!  % e$$AA e$$A<mAq!!  q!99c!Qii rrrexponentc F|dz |dz z} tj||}nP#tjj$r9}tj|||jd|||jfz|d}~wwxYw||z|zdkrt d|||fz||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))rBrMrNNotRelativePrimeErrorrr2)rrrphi_nrr3s rcalculate_keys_custom_exponentrsUq1u E  J  x / / : +j..   DM%& /     1 "" G8UVX]J^ ^    Q;s .A;4A66A;c.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)rrs rcalculate_keysrs *!Q0@ A AArc t|dz||\}} t|||\}}n#t$rYnwxYw?||||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 TrL)r)rrr2)rrrrrrrrs rgen_keysrsu,%1*mX>>A 3Aq8LLLFQ     D   aA:s 0 ==r@poolsizecF |dkrtddkrtdzdkrddlm dtdtf fd }ntjj}t |||| \}}}}||z} 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)parallelrr c2|S)N)r)getprime)rrrs rrznewkeys..getprime_func;s$$UX$>> >r)rr) r2rBrrTrErrr_r) rrrrrrrrrrrs ` @rnewkeysrs> rzz)))!||88CDDD!||       ? ? ? ? ? ? ? ? ? ? * E=8hWWWLQ1a AA aOOZ1aA66 77r)r_rr__main__d z%i timesz Doctests doneAborted)%rRrrVr rsa.primerBrsa.pem rsa.common rsa.randnumrsa.corerTypeVarrrr_rrErrTr\rr]rrrrr__all__rOdoctestrAcounttestmodfailurestestsprintKeyboardInterruptrrrrs& FN3m,,,d8d8d8d8d8d8d8d8Nb7b7b7b7b7 b7b7b7Jp9p9p9p9p9p9p9p9j251CM M M ?C5#:.M M  \#s( M M M M `ccSV\RUWZRZE[D Bc Bc Bfl38&< B B B B $  ?C5#:.   \#sC$% F$ 5858 585858 58  \)Z'( 58585858p 1 0 0 zNNN U3ZZ * *E / 1 1 Xu  aEeqjjj5())) o  is AE00FF