;iLdZddlZddlZddgZdededefdZd edefd Zd ed edefd Z d edefdZ dedefdZ dededefdZ e dkrYedddlZedD]1Zej\ZZernedzdkreredez2eddSdS)zNumerical functions related to primes. Implementation based on the book Algorithm Design by Michael T. Goodrich and Roberto Tamassia, 2002. Ngetprimeare_relatively_primepqreturnc,|dkr |||z}}|dk |S)zPReturns the greatest common divisor of p and q >>> gcd(48, 180) 12 r)rrs =C:\PYTHON\MyICR_Workspace\venv\Lib\site-packages\rsa/prime.pygcdr s* q&&QUA q&& Hnumbercttj|}|dkrdS|dkrdS|dkrdSdS)aReturns minimum number of rounds for Miller-Rabing primality testing, based on number bitsize. According to NIST FIPS 186-4, Appendix C, Table C.3, minimum number of rounds of M-R testing, using an error probability of 2 ** (-100), for different p, q bitsizes are: * p, q bitsize: 512; rounds: 7 * p, q bitsize: 1024; rounds: 4 * p, q bitsize: 1536; rounds: 3 See: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf iii )rsacommonbit_size)r bitsizes r get_primality_testing_roundsr'sHj!!&))G$q$q#~~q 2r nkcx|dkrdS|dz }d}|dzs|dz }|dz}|dzt|D]}tj|dz dz}t |||}|dks ||dz krHt|dz D](}t |d|}|dkrdS||dz krn)dSdS)a.Calculates whether n is composite (which is always correct) or prime (which theoretically is incorrect with error probability 4**-k), by applying Miller-Rabin primality testing. For reference and implementation example, see: https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test :param n: Integer to be tested for primality. :type n: int :param k: Number of rounds (witnesses) of Miller-Rabin testing. :type k: int :return: False if the number is composite, True if it's probably prime. :rtype: bool FrrT)rangerrandnumrandintpow)rrdr_axs r miller_rabin_primality_testingr&As" 1uuu AA A1u Q a1u 1XX K  A & & * 1aLL 66Q!a%ZZ q1u  AAq! AAvvuuuAEzz 55 4r ch|dkr|dvS|dzsdSt|}t||dzS)zReturns True if the number is prime, and False otherwise. >>> is_prime(2) True >>> is_prime(42) False >>> is_prime(41) True r>rrrrF)rr&)r rs r is_primer)vsP{{%% QJu %V,,A *&!a% 8 88r nbitscv|dksJ tj|}t|r|S1)aReturns a prime number that can be stored in 'nbits' bits. >>> p = getprime(128) >>> is_prime(p-1) False >>> is_prime(p) True >>> is_prime(p+1) False >>> from rsa import common >>> common.bit_size(p) == 128 True r)rrread_random_odd_intr))r*integers r rrsG 19999+11%88 G   N r r$bc.t||}|dkS)zReturns True if a and b are relatively prime, and False if they are not. >>> are_relatively_prime(2, 3) True >>> are_relatively_prime(2, 4) False r)r )r$r.r!s r rrs Aq A 6Mr __main__z'Running doctests 1000x or until failureidz%i timesz Doctests done)__doc__ rsa.commonr rsa.randnum__all__intr rboolr&r)rr__name__printdoctestrcounttestmodfailurestestsr r r r?s  - .  3  3  3     42c2c2d2222j9S9T99994CC8 C C D     z E 3444NNNt&&+GO--5   E 3;!    E*u$ % % % E/r