-
Notifications
You must be signed in to change notification settings - Fork 1
/
rsa
executable file
·73 lines (48 loc) · 1.42 KB
/
rsa
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
#!/usr/bin/env python3
from sys import argv, exit
from math import gcd
from random import randint
from time import time
def read_test_file(file_name):
"""Function to read number from file: one number per file"""
with open(file_name, "r", encoding="utf-8") as file:
lines = file.readlines()
number_to_factor = []
for line in lines:
# Check if the number has 100 or more digits
n = int(line.strip())
if n >= 10**99:
factors = pollard_rho(n)
print("{}={}*{}".format(n, factors[0], factors[1]))
else:
find_numbers(n)
return number_to_factor
def find_numbers(n):
"""Function to find factors of current number"""
for i in range(1, n):
if n % i == 0:
print("{}={}*{}".format(n, (n // i), i))
break
def pollard_rho(n):
"""Function to factor a number using the Pollard Rho algorithm"""
start_time = time()
x = randint(0, n - 1)
y = x
c = randint(1, n - 1)
d = 1
while d == 1:
if time() - start_time > 4:
exit(100)
x = (x*x + c) % n
y = (y*y + c) % n
y = (y*y + c) % n
d = gcd(abs(x - y), n)
if d == n:
return pollard_rho(n)
return (d, n // d)
def factors(ls):
"""Function to iterate between numbers in file"""
for i in ls:
find_numbers(i)
if len(argv) == 2:
factors(read_test_file(argv[1]))