Skip to content

Instantly share code, notes, and snippets.

@embe221ed
Last active October 7, 2020 12:20
Show Gist options
  • Save embe221ed/5ca031e630fe0c01356a7f9164cfe3b2 to your computer and use it in GitHub Desktop.
Save embe221ed/5ca031e630fe0c01356a7f9164cfe3b2 to your computer and use it in GitHub Desktop.
a python script which can be used for cracking simple RSA ciphers with known public key
#!/usr/bin/env python3
import argparse
import requests
from Crypto.PublicKey import RSA
from Crypto.Util.number import long_to_bytes
from base64 import b64decode
import gmpy
import sys
def read_pubkey(filename):
try:
pubkey_b64 = open(filename).read()
pubkey = b64decode(pubkey_b64)
pub = RSA.importKey(pubkey)
return pub
except Exception as e:
print('[!]' + str(e))
sys.exit(1)
def init_parser():
parser = argparse.ArgumentParser(description='Decrypt RSA message using public key')
parser.add_argument('public_key', type=str, help='name of base64 encoded file containing public key')
parser.add_argument('--message', type=str, help='enrypted message')
parser.add_argument('--encfile', type=str, help='name of base64 encoded file containing encrypted message')
parser.add_argument('-p', type=int, help='p factor')
parser.add_argument('-q', type=int, help='q factor')
return parser.parse_args()
def get_factors(n, args):
if args.p and args.q:
return int(args.p), int(args.q)
res = requests.get('http://factordb.com/api', params={"query": (n)})
factors = res.json()['factors']
return int(factors[0][0]), int(factors[1][0])
def sanity_checks(n, e, p, q, d):
print('[*] Checking n, p and q')
assert n == p * q
print('[*] Checking d')
assert 2 == pow(pow(2, e, n), d, n)
def get_message(args):
message = ''
if args.message:
message = args.message
if args.encfile:
try:
b64_msg = open(args.encfile).read()
message = b64decode(b64_msg)
except Exception as e:
print('[!]' + str(e))
data_int = int(message.hex(), 16)
return data_int
if __name__ == '__main__':
args = init_parser()
print('[*] RSA decryption tool')
print('[*] Written by h4ck1t')
if not args.message and not args.encfile:
print('What do you want do decrypt?')
sys.exit(0)
pub = read_pubkey(args.public_key)
n = pub.n
e = pub.e
p, q = get_factors(n, args)
d = gmpy.invert(e, (p-1)*(q-1))
sanity_checks(n, e, p, q, d)
data_int = get_message(args)
data_decoded = pow(data_int, d, n)
print('[*] Decoded data:')
print(long_to_bytes(data_decoded))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment