3 M(Y;@sdZdZdZdZddlZddlZddlZddlZddlZddl m Z ddl Z e j de e j ded d Zd d Zd dZddZddZddZddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Z d-d.Z!d/d0Z"d1d2Z#d3d4Z$d5d6Z%d7d8Z&d9d:Z'd;d<Z(d=d>Z)d?d@Z*dAdBZ+dCdDZ,dEdFZ-e dGkrxddl.Z.e.j/d2d@dDdBdFgZ0dS)HzDeprecated version of the RSA module .. deprecated:: 3.0 This submodule is deprecated and will be completely removed as of version 4.0. z;Sybren Stuvel, Marloes de Boer, Ivo Tamboer, and Barry Meadz 2010-02-08z2.0N)bytez4Insecure version of the RSA module is imported as %szNThis submodule is deprecated and will be completely removed as of version 4.0.cCsttjtj|dS)zBReturns the number of bits required to hold a specific long number)intmathceillog)numberr 6/private/tmp/pip-build-nl73fm5q/rsa/rsa/_version200.pybit_size+sr cCs2x,|dkr,||kr||}}|||}}qW|S)zOReturns the greatest common divisor of p and q >>> gcd(48, 180) 12 rr )pqr r r gcd0s   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)typetypesListType StringType TypeErrorord)bytesintegerrr r r bytes2int<s  rcCsVt|tjkpt|tjks$tdd}x(|dkrPdt|d@|f}|d}q*W|S)z0 Converts a number to a string of bytes zYou must pass a long or an intrz%s%sr)rrLongTypeIntTyperr)rstringr r r int2bytesLs  rcCst|tjkpt|tjks$tdd|ko6dknrHt|dSd|koZdknrlt|dSd|ko~d knrt|d S|d krtd S|d krtd Std|dS)zConverts a number in the range of 0 to 63 into base 64 digit character in the range of '0'-'9', 'A'-'Z', 'a'-'z','-','_'. zYou must pass a long or an intr 0 #7$=>-?_zInvalid Base64 value: %iN)rrrrrr ValueError)rr r r to64\s   r+cCst|tjkpt|tjks$tdd|ko6dknrD|dSd|koVdknrd|dSd|kovdknr|d S|d krd S|d krd Std|dS)znConverts an ordinal character value in the range of 0-9,A-Z,a-z,-,_ to a number in the range of 0-63. zYou must pass a long or an intr 9AZr#azr%r'r&r)r(zInvalid Base64 value: %iN)rrrrrr*)rr r r from64vsr1cCsVt|tjkpt|tjks$tdd}x(|dkrPdt|d@|f}|d}q*W|S)zsConverts a number to a string of base64 encoded characters in the range of '0'-'9','A'-'Z,'a'-'z','-','_'. zYou must pass a long or an intrrz%s%sr(@)rrrrrr+)rrr r r int2str64s  r3cCsdt|tjkpt|tjks$tdd}x6|D].}|d9}t|tjkrPt|}|t|7}q.W|S)zConverts a base64 encoded string into an integer. The chars of this string in in the range '0'-'9','A'-'Z','a'-'z','-','_' z You must pass a string or a listrr2)rrrrrrr1)rrrr r r str642ints r4cCs$ttj|d}tj|}t|S)zPReads a random integer of approximately nbits bits rounded up to whole bytesg @)rrrosurandomr)nbitsnbytesZ randomdatar r r read_random_ints r9cCsNd}||d}t|dd}t|d|d}tj||}t|||S)z9Returns a random integer x with minvalue <= x <= maxvalue r)r maxrandomrandintr9)ZminvaluemaxvalueZ min_nbitsrangeZ rangebytesZ rangebitsr7r r r r@s   r@cCs|dkr dSd}xd|dkrt|d@rP|d|dd?d@r@| }|||}}q||dd?d@rj| }|dL}qW|dkrdS|S)zoCalculates the value of the Jacobi symbol (a/b) where both a and b are positive integers, and b is odd rr;rr )abresultr r r jacobis  rGcCs2t|||}t||dd|}||kr.dSdS)zUReturns False if n is an Euler pseudo-prime with base x, and True otherwise. r;rFT)rGpow)xnjfr r r jacobi_witnesss rMcCs2x,t|D] }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 is composite, and True if it's probably prime. r;FT)rBr@rM)rJkirIr r r randomized_primality_testings  rPcCst|drdSdS)z>Returns True if the number is prime, and False otherwise. TF)rP)rr r r is_primes rRcCs$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. r;)r9rR)r7rr r r getprimes rScCst||}|dkS)zReturns True if a and b are relatively prime, and False if they are not. >>> are_relatively_prime(2, 3) 1 >>> are_relatively_prime(2, 4) 0 r;)r)rDrEdr r r are_relatively_primes rUcCs@||d}||d}t|}xt|}||ks"Pq"W||fS)z5Returns a tuple of two different primes of nbits bits)rS)r7ZpbitsZqbitsr r r r r find_p_q's  rWc Csd}d}d}d}|}|}xJ|dkrbt||}|||}}||||}}||||}}qW|dkrt||7}|dkr||7}|||fS)z@Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb rr;)long) rDrErIyZlxZlyZoaobr r r r extended_gcd2s   r[c Cs||}|d|d}x,tdt|d}t||rt||rPqWt||\}}}|dksntd||f|dkr~td|||dkstd|||f||fS)zaCalculates an encryption and a decryption key for p and q, and returns them as a tuple (e, d)r;iz.e (%d) and phi_n (%d) are not relatively primerz1New extended_gcd shouldn't return negative valuesz6e (%d) and i (%d) are not mult. inv. modulo phi_n (%d))r>rSrUr[ Exception) r r r7rJZphi_nerTrOrKr r r calculate_keysIsr_cCs(t|\}}t|||\}}||||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. )rWr_)r7r r r^rTr r r gen_keysbs r`cCs4td|}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: ....). r)r^rJ)rTr r )r>r`)r7r r r^rTr r r newkeysms racCsht|tjkrt|}t|tjk r,td|dks<||krDtdt|d}|d|>7}t|||S)z@Encrypts a message using encryption key 'ekey', working modulo nzYou must pass a long or intrzThe message is too longrr;) rrrrXrr OverflowErrorr rH)messageZekeyrJsafebitr r r encrypt_intys  recCs(t|||}t|d}|d|>8}|S)zLDecrypts a cypher text using the decryption key 'dkey', working modulo nrr;)rHr )Z cyphertextZdkeyrJrcrdr r r decrypt_ints   rfcCs.g}x|D]}|jt|q Wdj|}|S)zAbase64encodes chops and combines them into a ',' delimited string,)appendr3join)chopschipsvalueencodedr r r encode64chopss   rncCs.|jd}g}x|D]}|jt|qW|S)z9base64decodes and makes a ',' delimited string into chopsrg)splitrhr4)rrkrjr r r decode64chopss   rpcCst|}|d}t|d}|d}||}||dkr@|d7}g} xBt|D]6} | |} || | |} t| } | j|| ||qNWt| S)aChops the 'message' into integers that fit into n, leaving room for a safebit to be added to ensure that all messages fold during exponentiation. The MSB of the number n is not independant modulo n (setting it could cause overflow), so use the next lower bit for the safebit. Therefore reserve 2-bits in the number n for non-data bits. Calls specified encryption function for each chop. Used by 'encrypt' and 'sign'. r=rrr;)lenr rBrrhrn)rckeyrJfuncrefZmsglenZmbitsr7r8blockscypherZbindexoffsetblockrlr r r chopstrings   rxcCs6d}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)rpr)rrrrJrsrcrjZcpartZmpartr r r gluechopss   rycCs&d|krtdt||d|dtS)z5Encrypts a string 'message' with the public key 'key'rJz(You must use the public key with encryptr^)r]rxre)rcrrr r r encryptsrzcCs.d|krtdt||d|d|dtS)z3Signs a string 'message' with the private key 'key'r z&You must use the private key with signrTr )r]rxre)rcrrr r r signsr{cCs.d|krtdt||d|d|dtS)z5Decrypts a string 'cypher' with the private key 'key'r z)You must use the private key with decryptrTr )r]ryrf)rurrr r r decryptsr|cCs&d|krtdt||d|dtS)z4Verifies a string 'cypher' with the public key 'key'rJz'You must use the public key with verifyr^)r]ryrf)rurrr r r verifysr}__main__)1__doc__ __author____date__ __version__rr5r?sysrZ rsa._compatrwarningswarn__name__DeprecationWarningr rrrr+r1r3r4r9r@rGrMrPrRrSrUrWr[r_r`rarerfrnrprxryrzr{r|r}doctesttestmod__all__r r r r s`