]>
gitweb.pimeys.fr Git - NK2015_Client_Python_Alpha.git/blob - rsa_source/rsa/prime.py
1 # -*- coding: utf-8 -*-
3 # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 '''Numerical functions related to primes.'''
19 __all__
= [ 'getprime', 'are_relatively_prime']
24 """Returns the greatest common divisor of p and q
31 if p
< q
: (p
,q
) = (q
,p
)
37 """Calculates the value of the Jacobi symbol (a/b) where both a and b are
38 positive integers, and b is odd
45 if ((a
-1)*(b
-1) >> 2) & 1:
49 if (((b
* b
) - 1) >> 3) & 1:
55 def jacobi_witness(x
, n
):
56 """Returns False if n is an Euler pseudo-prime with base x, and
61 f
= pow(x
, (n
- 1) // 2, n
)
63 if j
== f
: return False
66 def randomized_primality_testing(n
, k
):
67 """Calculates whether n is composite (which is always correct) or
68 prime (which is incorrect with error probability 2**-k)
70 Returns False if the number is composite, and True if it's
74 # 50% of Jacobi-witnesses can report compositness of non-prime numbers
77 x
= rsa
.randnum
.randint(n
-1)
78 if jacobi_witness(x
, n
): return False
83 """Returns True if the number is prime, and False otherwise.
91 return randomized_primality_testing(number
, 6)
94 """Returns a prime number that can be stored in 'nbits' bits.
104 >>> from rsa import common
105 >>> common.bit_size(p) <= 128
111 integer
= rsa
.randnum
.read_random_int(nbits
)
117 if is_prime(integer
):
123 def are_relatively_prime(a
, b
):
124 """Returns True if a and b are relatively prime, and False if they
127 >>> are_relatively_prime(2, 3)
129 >>> are_relatively_prime(2, 4)
136 if __name__
== '__main__':
137 print 'Running doctests 1000x or until failure'
140 for count
in range(1000):
141 (failures
, tests
) = doctest
.testmod()
145 if count
and count
% 100 == 0:
146 print '%i times' % count
148 print 'Doctests done'