Mind your Ps and Qs

This commit is contained in:
Maxime Vorwerk
2024-06-06 13:03:19 +02:00
parent f5eb82885e
commit ca4efb2ab8
2 changed files with 62 additions and 0 deletions

55
mind_your_ps_and_qs/sol.py Executable file
View File

@@ -0,0 +1,55 @@
#!/usr/bin/python3
import math
def totient(p, q):
tot, rem = divmod((p-1) * (q-1), math.gcd(p-1, q-1))
if rem != 0:
raise Exception("totient calc failed")
return tot
def egcd(a, b):
x0, x1, y0, y1 = 0, 1, 1, 0
while a != 0:
(q, a), b = divmod(b, a), a
y0, y1 = y1, y0 - q * y1
x0, x1 = x1, x0 - q * x1
return b, x0, x1
# https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm
def mod_inv(d, lambda_n):
g, x, _ = egcd(d, lambda_n)
if g != 1:
raise Exception("gcd(d, lambda_n != !")
return x % lambda_n
def rsa(text, key, n):
return pow(text, key, n)
with open("values", 'r') as f:
lines = f.readlines()
C = int(lines[1][3:])
n = int(lines[2][3:])
e = int(lines[3][3:])
p = int(lines[4][3:])
q = int(lines[5][3:])
if p*q == n:
print("factoring correct")
else:
print("factoring incorrect")
lambda_n = totient(p, q)
d = mod_inv(e, lambda_n)
#d = pow(d, -1, lambda_n)
res = rsa(C, d, n)
text = ''
while (char := (res % 256)) != 0:
text = chr(char) + text;
res >>= 8
print(text)

7
mind_your_ps_and_qs/values Executable file
View File

@@ -0,0 +1,7 @@
Decrypt my super sick RSA:
c: 861270243527190895777142537838333832920579264010533029282104230006461420086153423
n: 1311097532562595991877980619849724606784164430105441327897358800116889057763413423
e: 65537
p: 1955175890537890492055221842734816092141
q: 670577792467509699665091201633524389157003
factored using factordb.com