Skip to content

Commit e3aa0f6

Browse files
Jiang-zzzcclauss
authored andcommitted
fix implementation errors. (TheAlgorithms#1568)
I revised my implementation and found out that I have miss a inner loop for t. x and y should be recalculated everytime when t is divisble by 2. I have also included a more readble source for this algorithm.
1 parent ea9bf0a commit e3aa0f6

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

ciphers/rsa_factorization.py

+13-8
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
The program can efficiently factor RSA prime number given the private key d and
55
public key e.
66
Source: on page 3 of https://crypto.stanford.edu/~dabo/papers/RSA-survey.pdf
7+
More readable source: https://www.di-mgt.com.au/rsa_factorize_n.html
78
large number can take minutes to factor, therefore are not included in doctest.
89
"""
910
import math
@@ -15,7 +16,7 @@ def rsafactor(d: int, e: int, N: int) -> List[int]:
1516
"""
1617
This function returns the factors of N, where p*q=N
1718
Return: [p, q]
18-
19+
1920
We call N the RSA modulus, e the encryption exponent, and d the decryption exponent.
2021
The pair (N, e) is the public key. As its name suggests, it is public and is used to
2122
encrypt messages.
@@ -35,13 +36,17 @@ def rsafactor(d: int, e: int, N: int) -> List[int]:
3536
while p == 0:
3637
g = random.randint(2, N - 1)
3738
t = k
38-
if t % 2 == 0:
39-
t = t // 2
40-
x = (g ** t) % N
41-
y = math.gcd(x - 1, N)
42-
if x > 1 and y > 1:
43-
p = y
44-
q = N // y
39+
while True:
40+
if t % 2 == 0:
41+
t = t // 2
42+
x = (g ** t) % N
43+
y = math.gcd(x - 1, N)
44+
if x > 1 and y > 1:
45+
p = y
46+
q = N // y
47+
break # find the correct factors
48+
else:
49+
break # t is not divisible by 2, break and choose another g
4550
return sorted([p, q])
4651

4752

0 commit comments

Comments
 (0)