Skip to content

Instantly share code, notes, and snippets.

@Reelix
Last active February 16, 2024 22:59
Show Gist options
  • Save Reelix/fff0378249a9c8d787e3dba4b1899ba1 to your computer and use it in GitHub Desktop.
Save Reelix/fff0378249a9c8d787e3dba4b1899ba1 to your computer and use it in GitHub Desktop.
Python3 Simple RSA CTF Solver
# python3 -m pip install pycryptodome==3.4.3
from Crypto.Util.number import inverse, long_to_bytes
import decimal, binascii
# If you have the id_rsa.pub or equivalent
# ssh-keygen -f id_rsa.pub -e -m PKCS8 > id_rsa.pem
# If you have a private key (pem) file
# - http://certificate.fyicenter.com/2145_FYIcenter_Public_Private_Key_Decoder_and_Viewer.html
# -- Fill in n, e, d, p, q (Note: numeric values of n,d,p,q - Not displayed hex values)
# -- Convert hex to decimal over at: https://www.binaryhexconverter.com/hex-to-decimal-converter
n = 0 # Enter given n value here - Leave as 0 if not available
e = 0 # Enter given e value here - Required
c = 0 # Enter given c value here - Leave as 0 if not available (If 0, will assume you have a cipher file named cipher)
d = 0 # Enter given d value here - Leave as 0 if not available
# If you have n
# - Go to http://factordb.com/ and enter in n
# - Under "Number", p = left, q = right. If they have ^2 on them, add **2 to the end of the number
# If you have p and q, just enter them
p = 0
q = 0
### ###
### Do not edit below this line ###
### ###
if (n == 0):
n = p * q
# Cubed Root Attack (Thanks John!)
if e == 3:
decimal.getcontext().prec = 3000
c_decimal = decimal.Decimal(str(c))
m = c_decimal ** (decimal.Decimal('1') / 3)
m = int(m) + 1
result = long_to_bytes(m)
print("Possible Solution: " + result.decode("utf-8"))
if p != 0 and q != 0:
# They match - Different calc
if p == q:
phi = p * (p - 1)
else:
phi = (p - 1) * (q - 1)
# Either solving for c or d
if d == 0:
d = inverse(e,phi)
if c == 0:
with open("cipher", "rb") as f:
data = f.read()
c = int(binascii.hexlify(data), 16)
# We should have everything now
m = pow( c, d, n )
print(long_to_bytes(m))
@Reelix
Copy link
Author

Reelix commented Feb 16, 2024

Generate private key from n, p, q, and e

python3 rsatool.py -n CHANGEME -p CHANGEME -q CHANGEME -e CHANGEME(Probs 65537) -f PEM -o priv.key

chmod 600 priv.key

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