rsa lesson added
This commit is contained in:
45
training/h4tum/Intro_to_RSA/challenge/Fermat/1.py
Normal file
45
training/h4tum/Intro_to_RSA/challenge/Fermat/1.py
Normal file
@@ -0,0 +1,45 @@
|
||||
from Crypto.Util.number import inverse, getPrime, bytes_to_long, long_to_bytes
|
||||
from sympy import nextprime
|
||||
import os
|
||||
import math
|
||||
|
||||
|
||||
flag = "h4tum{...}"
|
||||
m = bytes_to_long(flag.encode())
|
||||
|
||||
p : int = getPrime(512)
|
||||
diff = int.from_bytes(os.urandom(16), 'big')
|
||||
q : int = nextprime(p - diff)
|
||||
n = p * q
|
||||
phi = (p - 1) * (q - 1)
|
||||
e = 65537
|
||||
d = inverse(e, phi)
|
||||
|
||||
ciphertext = pow(m, e, n)
|
||||
|
||||
print(f"Here is the public key:\nn = {n}\ne = {e}")
|
||||
print(f"\nHere is the encrypted flag:\n{ciphertext}")
|
||||
|
||||
t = math.isqrt(n)
|
||||
|
||||
for i in range((n+1)//2 - t + 1):
|
||||
val = (t + i)**2 - n
|
||||
if val > 0:
|
||||
root = math.isqrt(val)
|
||||
if root * root == val:
|
||||
r = math.isqrt((t+i)**2 - n)
|
||||
rec_p = (t+i) - r
|
||||
rec_q = (t+i) + r
|
||||
rec_phi = (rec_p-1) * (rec_q-1)
|
||||
rec_d = inverse(e, rec_phi)
|
||||
plain_text = pow(ciphertext, rec_d, n)
|
||||
print("We recovered d yay")
|
||||
print(f"Cracked flag: {long_to_bytes(plain_text)}")
|
||||
break
|
||||
|
||||
|
||||
|
||||
|
||||
# Here is the public key:
|
||||
# Here is the encrypted flag:
|
||||
# 13158607848927768767396122915610010628021182023103983078656746030071489695567187651581550866461152226282740548654306454938594539749024910072164328096542525661951926739718955208177780816184581302682602611753650161772357698132248994074563798067850345731371433620586869504864647385937063506440611160969011596274
|
||||
Reference in New Issue
Block a user