Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/test/test_pseudoprimes.py
2587 views
1
import os
2
import sys
3
from unittest import TestCase
4
5
path = os.path.dirname(os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
6
if sys.path[1] != path:
7
sys.path.insert(1, path)
8
9
from attacks.pseudoprimes import miller_rabin
10
11
12
class TestPseudoprimes(TestCase):
13
def _miller_rabin(self, n, bases):
14
assert n > 3
15
r = 0
16
d = n - 1
17
while d % 2 == 0:
18
r += 1
19
d //= 2
20
21
for a in bases:
22
x = pow(a, d, n)
23
if x == 1 or x == n - 1:
24
continue
25
for _ in range(r - 1):
26
x = pow(x, 2, n)
27
if x == n - 1:
28
break
29
else:
30
return False
31
return True
32
33
def test_miller_rabin(self):
34
bases = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
35
n, p1, p2, p3 = miller_rabin.generate_pseudoprime(bases, min_bit_length=400)
36
self.assertIsInstance(n, int)
37
self.assertIsInstance(p1, int)
38
self.assertIsInstance(p2, int)
39
self.assertIsInstance(p3, int)
40
self.assertGreaterEqual(n.bit_length(), 400)
41
self.assertEqual(n, p1 * p2 * p3)
42
self.assertTrue(self._miller_rabin(n, bases))
43
44
bases = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61]
45
n, p1, p2, p3 = miller_rabin.generate_pseudoprime(bases, min_bit_length=600)
46
self.assertIsInstance(n, int)
47
self.assertIsInstance(p1, int)
48
self.assertIsInstance(p2, int)
49
self.assertIsInstance(p3, int)
50
self.assertGreaterEqual(n.bit_length(), 600)
51
self.assertEqual(n, p1 * p2 * p3)
52
self.assertTrue(self._miller_rabin(n, bases))
53
54