-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_attack.py
More file actions
114 lines (98 loc) · 1.8 KB
/
simple_attack.py
File metadata and controls
114 lines (98 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# -*- coding: utf-8 -*-
import random
def modular_exp(a, b, n):
res = 1
while b > 0:
if b & 1 == 1:
res = (res * a) % n
a = (a * a) % n
b >>= 1
return res
def gen_rand(bit_length):
bits = [random.randint(0,1) for _ in range(bit_length - 2)]
ret = 1
for b in bits:
ret = ret * 2 + int(b)
return ret * 2 + 1
def mr_primary_test(n, k=100):
if n == 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
d = n - 1
s = 0
while d % 2 != 0:
d /= 2
s += 1
r = [random.randint(1, n - 1) for _ in range(k)]
for a in r:
if modular_exp(a, d, n) != 1:
pl = [(2 ** rr) * d for rr in range(s)]
flg = True
for p in pl:
if modular_exp(a, p, n) == 1:
flg = False
break
if flg:
return False
return True
def gen_prime(bit):
while True:
ret = gen_rand(bit)
if mr_primary_test(ret):
break
return ret
def gcd(x, y):
if x < y:
x, y = y, x
if y == 0:
return x
return gcd(y, x % y)
def exgcd(x, y):
c0, c1 = x, y
a0, a1 = 1, 0
b0, b1 = 0, 1
while c1 != 0:
m = c0 % c1
q = c0 // c1
c0, c1 = c1, m
a0, a1 = a1, (a0 - q * a1)
b0, b1 = b1, (b0 - q * b1)
return c0, a0, b0
def gen_d(e, l):
_, x, _ = exgcd(e, l)
return x % l
# ロー法
def rho_algo(n, x, y, i):
d = 1
while d == 1:
x = (x * x + 1) % n
y = (y * y + 1) % n
y = (y * y + 1) % n
d = gcd(abs(x - y), n)
return d
def simple(n, e, c):
p = rho_algo(n, 2, 2, 0)
q = n / p
d = e
phi = (p - 1) * (q - 1)
while d % phi != 1:
d += e
return (p, q, d // e)
if __name__ == '__main__':
e = 65537
m = 123456789
p = gen_prime(10)
q = gen_prime(10)
d = gen_d(e, (p-1)*(q-1))
n = p * q
c = modular_exp(m, e, n)
# n, e, c -> p, q, d
print("その1,2 simple attack")
print("e:", e, "n:", n)
p, q, d = simple(n, e, c)
print("complete!")
print("prime:", p, q)
print()