Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(127)

Side by Side Diff: third_party/google-endpoints/rsa/prime.py

Issue 2666783008: Add google-endpoints to third_party/. (Closed)
Patch Set: Created 3 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « third_party/google-endpoints/rsa/pkcs1.py ('k') | third_party/google-endpoints/rsa/randnum.py » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # https://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 """Numerical functions related to primes.
18
19 Implementation based on the book Algorithm Design by Michael T. Goodrich and
20 Roberto Tamassia, 2002.
21 """
22
23 import rsa.randnum
24
25 __all__ = ['getprime', 'are_relatively_prime']
26
27
28 def gcd(p, q):
29 """Returns the greatest common divisor of p and q
30
31 >>> gcd(48, 180)
32 12
33 """
34
35 while q != 0:
36 (p, q) = (q, p % q)
37 return p
38
39
40 def miller_rabin_primality_testing(n, k):
41 """Calculates whether n is composite (which is always correct) or prime
42 (which theoretically is incorrect with error probability 4**-k), by
43 applying Miller-Rabin primality testing.
44
45 For reference and implementation example, see:
46 https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
47
48 :param n: Integer to be tested for primality.
49 :type n: int
50 :param k: Number of rounds (witnesses) of Miller-Rabin testing.
51 :type k: int
52 :return: False if the number is composite, True if it's probably prime.
53 :rtype: bool
54 """
55
56 # prevent potential infinite loop when d = 0
57 if n < 2:
58 return False
59
60 # Decompose (n - 1) to write it as (2 ** r) * d
61 # While d is even, divide it by 2 and increase the exponent.
62 d = n - 1
63 r = 0
64
65 while not (d & 1):
66 r += 1
67 d >>= 1
68
69 # Test k witnesses.
70 for _ in range(k):
71 # Generate random integer a, where 2 <= a <= (n - 2)
72 a = rsa.randnum.randint(n - 4) + 2
73
74 x = pow(a, d, n)
75 if x == 1 or x == n - 1:
76 continue
77
78 for _ in range(r - 1):
79 x = pow(x, 2, n)
80 if x == 1:
81 # n is composite.
82 return False
83 if x == n - 1:
84 # Exit inner loop and continue with next witness.
85 break
86 else:
87 # If loop doesn't break, n is composite.
88 return False
89
90 return True
91
92
93 def is_prime(number):
94 """Returns True if the number is prime, and False otherwise.
95
96 >>> is_prime(2)
97 True
98 >>> is_prime(42)
99 False
100 >>> is_prime(41)
101 True
102 >>> [x for x in range(901, 1000) if is_prime(x)]
103 [907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
104 """
105
106 # Check for small numbers.
107 if number < 10:
108 return number in [2, 3, 5, 7]
109
110 # Check for even numbers.
111 if not (number & 1):
112 return False
113
114 # According to NIST FIPS 186-4, Appendix C, Table C.3, minimum number of
115 # rounds of M-R testing, using an error probability of 2 ** (-100), for
116 # different p, q bitsizes are:
117 # * p, q bitsize: 512; rounds: 7
118 # * p, q bitsize: 1024; rounds: 4
119 # * p, q bitsize: 1536; rounds: 3
120 # See: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
121 return miller_rabin_primality_testing(number, 7)
122
123
124 def getprime(nbits):
125 """Returns a prime number that can be stored in 'nbits' bits.
126
127 >>> p = getprime(128)
128 >>> is_prime(p-1)
129 False
130 >>> is_prime(p)
131 True
132 >>> is_prime(p+1)
133 False
134
135 >>> from rsa import common
136 >>> common.bit_size(p) == 128
137 True
138 """
139
140 assert nbits > 3 # the loop wil hang on too small numbers
141
142 while True:
143 integer = rsa.randnum.read_random_odd_int(nbits)
144
145 # Test for primeness
146 if is_prime(integer):
147 return integer
148
149 # Retry if not prime
150
151
152 def are_relatively_prime(a, b):
153 """Returns True if a and b are relatively prime, and False if they
154 are not.
155
156 >>> are_relatively_prime(2, 3)
157 True
158 >>> are_relatively_prime(2, 4)
159 False
160 """
161
162 d = gcd(a, b)
163 return d == 1
164
165
166 if __name__ == '__main__':
167 print('Running doctests 1000x or until failure')
168 import doctest
169
170 for count in range(1000):
171 (failures, tests) = doctest.testmod()
172 if failures:
173 break
174
175 if count and count % 100 == 0:
176 print('%i times' % count)
177
178 print('Doctests done')
OLDNEW
« no previous file with comments | « third_party/google-endpoints/rsa/pkcs1.py ('k') | third_party/google-endpoints/rsa/randnum.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698