3 M(Y- @sdZdZdZdZy ddlZWnek r8ddlZYnXddlmZmZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlmZddlZejdeejd ed d Zd d ZddZddZddZddZddZddZddZddZddZ d d!Z!d"d#Z"d$d%Z#d&d'Z$d(d)Z%d*d+Z&d,d-Z'd.d/Z(d0d1Z)d2d3Z*d4d5Z+d6d7Z,d8d9Z-d:d;Z.dd?Z0d@dAZ1dBdCZ2dDdEZ3dFdGZ4edHkrddl5Z5e5j6d/dAdEdCdGgZ7dS)Ia_Deprecated version of the RSA module .. deprecated:: 2.0 This submodule is deprecated and will be completely removed as of version 4.0. Module for calculating large primes, and RSA encryption, decryption, signing and verification. Includes generating public and private keys. WARNING: this code implements the mathematics of RSA. It is not suitable for real-world secure cryptography purposes. It has not been reviewed by a security expert. It does not include padding of data. There are many ways in which the output of this module, when used without any modification, can be sucessfully attacked. z.Sybren Stuvel, Marloes de Boer and Ivo Tamboerz 2010-02-05z1.3.3N)dumpsloads)bytez@Insecure version of the RSA module is imported as %s, be carefulzNThis submodule is deprecated and will be completely removed as of version 4.0.cCs0||krt||S|dkr|St|t||S)zNReturns the greatest common divisor of p and q >>> gcd(42, 6) 6 r)gcdabs)pqr 6/private/tmp/pip-build-nl73fm5q/rsa/rsa/_version133.pyr?s  rcCs`t|tjkpt|tjks$tdd}x2|D]*}|d9}t|tjkrPt|}||7}q.W|S)z7Converts a list of bytes or a string to an integer z You must pass a string or a listr)typetypesZListTypeZ StringType TypeErrorord)bytesintegerrr r r bytes2intJs  rcCsVt|tjkpt|tjks$tdd}x(|dkrPdt|d@|f}|d}q*W|S)z+Converts a number to a string of bytes zYou must pass a long or an intrz%s%sr )r r LongTypeIntTyperr)numberstringr r r int2bytesZs  rcCsZ||}g}x"|dkr.|j|d@|d?}qWx$|rT|j}|||d|}q2W|S)zCalculates r = a^p mod n )appendpop)arnresultZ remaindersremr r r fast_exponentiationis  r"cCst|d}tj|}t|S)zPReads a random integer of approximately nbits bits rounded up to whole bytesg @)ceilosurandomr)nbitsnbytesZ randomdatar r r read_random_intvs  r(cCsttj|S)zceil(x) -> int(math.ceil(x)))intmathr#)xr r r r#~sr#cCsNd}||}ttj|dd}t|d|d}tj||}t|||S)z9Returns a random integer x with minvalue <= x <= maxvalue rg @)r#r*logmaxrandomrandintr()ZminvaluemaxvalueZ min_nbitsrangeZ rangebytesZ rangebitsr&r r r r1s  r1cCstd|d}t||d|S)zPReturns 1 if p may be prime, and something else if p definitely is not primer)r1r")rrr r r fermat_little_theoremsr4cCs~||dkrdSd}xd|dkrx|d@rT|d|dd?d@rD| }|||}}q|ddd?d@rn| }|d?}qW|S)z4Calculates the value of the Jacobi symbol (a/b) rrrr )rbr r r r jacobis   r7cCs2t|||}t||dd|}||kr.dSdS)zUReturns False if n is an Euler pseudo-prime with base x, and True otherwise. rrFT)r7r")r+rjfr r r jacobi_witnesss r:cCsRd}t|tjd|d}x0t|dD] }td|d}t||r*dSq*WdS)zCalculates whether n is composite (which is always correct) or prime (which is incorrect with error probability 2**-k) Returns False if the number if composite, and True if it's probably prime. g?rrFT)r#r*r.r3r1r:)rkrtir+r r r randomized_primality_testings r>cCst|drdSdS)z>Returns True if the number is prime, and False otherwise. TF)r>)rr r r is_primes r@cCs6ttj|d}xt|}|dO}t|rPqW|S)zxReturns a prime number of max. 'math.ceil(nbits/8)*8' bits. In other words: nbits is rounded up to whole bytes. g @r)r)r*r#r(r@)r&r'rr r r getprimesrAcCst||}|dkS)zQReturns True if a and b are relatively prime, and False if they are not. r)r)rr6dr r r are_relatively_primes rCcCs(t|}xt|}||ks Pq W||fS)z5Returns a tuple of two different primes of nbits bits)rA)r&rrr r r find_p_qs rDcCsL|dkr|ddfSt||}t||}t||\}}}|||||fS)z@Returns a tuple (d, i, j) such that d = gcd(a, b) = ia + jb rr)rlongextended_euclid_gcd)rr6rrrBr;lr r r rFs    rFc Cs||}|d|d}x,ttd|d}t||rt||rPqWt||\}}}|dksntd||f|||dkstd|||f||fS)zaCalculates an encryption and a decryption key for p and q, and returns them as a tuple (e, d)rr-rz.e (%d) and phi_n (%d) are not relatively primez6e (%d) and i (%d) are not mult. inv. modulo phi_n (%d))rAr/rCrF Exception) rrr&rZphi_nerBr=r8r r r calculate_keyssrKcCs8x*t|\}}t|||\}}|dkrPqW||||fS)z|Generate RSA keys of nbits bits. Returns (p, q, e, d). Note: this can take a long time, depending on the key size. r)rDrK)r&rrrJrBr r r gen_keys,s  rLcCs*t|\}}}}|||d|||dfS)zGenerates public and private keys, and returns them as (pub, priv). The public key consists of a dict {e: ..., , n: ....). The private key consists of a dict {d: ...., p: ...., q: ....). )rJr)rBrr)rL)r&rrrJrBr r r gen_pubpriv_keys<srMcCstt|tjkrtt|||St|tjk r4td|dkrhtjtj |dtjtj |dkrht dt |||S)zDEncrypts a message using encryption key 'ekey', working modulo nzYou must pass a long or an intrrzThe message is too long) r r r encrypt_intrErrr*floorr. OverflowErrorr")messageekeyrr r r rNHs$rNcCs t|||S)zLDecrypts a cypher text using the decryption key 'dkey', working modulo n)rN)Z cyphertextdkeyrr r r decrypt_intXsrTcCs t|||S)z2Signs 'message' using key 'dkey', working modulo n)rT)rQrSrr r r sign_int^srUcCs t|||S)z4verifies 'signed' using key 'ekey', working modulo n)rN)signedrRrr r r verify_intcsrWcCs tjt|}tj|}|jS)z-Pickles and base64encodes it's argument chops)zlibcompressrbase64 encodestringstrip)chopsvalueencodedr r r picklechopshs r`cCsttjtj|S)z:base64decodes and unpickes it's argument string into chops)rrX decompressrZ decodestring)rr r r unpicklechopsosrccCst|}|d}ttjtj|d}|d}||}||dkrJ|d7}g} xBt|D]6} | |} || | |} t| } | j|| ||qXWt| S)zSplits 'message' into chops that are at most as long as n, converts these into integers, and calls funcref(integer, key, n) for each chop. Used by 'encrypt' and 'sign'. r-rrr) lenr)r*rOr.r3rrr`)rQkeyrfuncrefZmsglenZmbitsr&r'blockscypherZbindexoffsetblockr^r r r chopstringts rkcCs6d}t|}x$|D]}||||}|t|7}qW|S)zGlues chops back together into a string. calls funcref(integer, key, n) for each chop. Used by 'decrypt' and 'verify'. r)rcr)r]rerrfrQZcpartZmpartr r r gluechopss   rlcCst||d|dtS)z5Encrypts a string 'message' with the public key 'key'rJr)rkrN)rQrer r r encryptsrmcCst||d|d|dtS)z3Signs a string 'message' with the private key 'key'rBrr)rkrT)rQrer r r signsrncCst||d|d|dtS)z,Decrypts a cypher with the private key 'key'rBrr)rlrT)rhrer r r decryptsrocCst||d|dtS)z+Verifies a cypher with the public key 'key'rJr)rlrN)rhrer r r verifysrp__main__)8__doc__ __author____date__ __version__cPicklepickle ImportErrorrrrZr*r$r0sysr rXZ rsa._compatrwarningswarn__name__DeprecationWarningrrrr"r(r#r1r4r7r:r>r@rArCrDrFrKrLrMrNrTrUrWr`rcrkrlrmrnrorpdoctesttestmod__all__r r r r sp