Skip to content

Instantly share code, notes, and snippets.

@ddddavidee
Last active April 1, 2022 14:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ddddavidee/b34c2b67757a54ce75cb to your computer and use it in GitHub Desktop.
Save ddddavidee/b34c2b67757a54ce75cb to your computer and use it in GitHub Desktop.
from math import gcd #for gcd function (or easily implementable to avoid import)
import random #for random elements drawing in RecoverPrimeFactors
def failFunction():
print("Prime factors not found")
def outputPrimes(a, n):
p = gcd(a, n)
q = int(n // p)
if p > q:
p, q = q, p
print("Found factors p and q")
print("p = {0}".format(str(p)))
print("q = {0}".format(str(q)))
return p,q
def RecoverPrimeFactors(n, e, d):
"""The following algorithm recovers the prime factor
s of a modulus, given the public and private
exponents.
Function call: RecoverPrimeFactors(n, e, d)
Input: n: modulus
e: public exponent
d: private exponent
Output: (p, q): prime factors of modulus"""
k = d * e - 1
if k % 2 == 1:
failFunction()
return 0, 0
else:
t = 0
r = k
while(r % 2 == 0):
r = int(r // 2)
t += 1
for i in range(1, 101):
g = random.randint(0, n) # random g in [0, n-1]
y = pow(g, r, n)
if y == 1 or y == n - 1:
continue
else:
for j in range(1, t): # j \in [1, t-1]
x = pow(y, 2, n)
if x == 1:
p, q = outputPrimes(y - 1, n)
return p, q
elif x == n - 1:
continue
y = x
x = pow(y, 2, n)
if x == 1:
p, q = outputPrimes(y - 1, n)
return p, q
@ddddavidee
Copy link
Author

Two small-sized tests:

RecoverPrimeFactors(1237*353567, 7, 249718615)
Found factors p and q
p = 1237
q = 353567
Out[67]: (1237, 353567)

In [68]: RecoverPrimeFactors(143, 7, 103)
Found factors p and q
p = 11
q = 13
Out[68]: (11, 13)

@giacom0c
Copy link

Line 36, should be r = r // 2

@ddddavidee
Copy link
Author

Line 36, should be r = r // 2

grazie!

@Hong5489
Copy link

At line 9 should be q = n // p

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment