Skip to content

Commit db515e5

Browse files
Jiang-zzzcclauss
authored andcommitted
added rsa_factorization.py (#1556)
* added RSA_factorization.py This algorithm can effectively factor RSA large prime N given public key e and private key d. * Rename RSA_factorization.py to rsa_factorization.py * Add definitions for d, e, and N
1 parent ad2db80 commit db515e5

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

ciphers/rsa_factorization.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
An RSA prime factor algorithm.
3+
4+
The program can efficiently factor RSA prime number given the private key d and
5+
public key e.
6+
Source: on page 3 of https://crypto.stanford.edu/~dabo/papers/RSA-survey.pdf
7+
large number can take minutes to factor, therefore are not included in doctest.
8+
"""
9+
import math
10+
import random
11+
from typing import List
12+
13+
14+
def rsafactor(d: int, e: int, N: int) -> List[int]:
15+
"""
16+
This function returns the factors of N, where p*q=N
17+
Return: [p, q]
18+
19+
We call N the RSA modulus, e the encryption exponent, and d the decryption exponent.
20+
The pair (N, e) is the public key. As its name suggests, it is public and is used to
21+
encrypt messages.
22+
The pair (N, d) is the secret key or private key and is known only to the recipient
23+
of encrypted messages.
24+
25+
>>> rsafactor(3, 16971, 25777)
26+
[149, 173]
27+
>>> rsafactor(7331, 11, 27233)
28+
[113, 241]
29+
>>> rsafactor(4021, 13, 17711)
30+
[89, 199]
31+
"""
32+
k = d * e - 1
33+
p = 0
34+
q = 0
35+
while p == 0:
36+
g = random.randint(2, N - 1)
37+
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
45+
return sorted([p, q])
46+
47+
48+
if __name__ == "__main__":
49+
import doctest
50+
51+
doctest.testmod()

0 commit comments

Comments
 (0)