Path: blob/master/RSA-encryption/Attack-Retrieve-Modulus/Challenges/Lost-Key/rsa.py
1402 views
#!/usr/bin/env python1from Crypto.Util.number import *2from gmpy2 import *3import os,sys45sys.stdin = os.fdopen(sys.stdin.fileno(), 'r', 0)6sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)78def genKey():9p = getPrime(512)10q = getPrime(512)11n = p*q12phi = (p-1)*(q-1)13while True:14e = getRandomInteger(40)15if gcd(e,phi) == 1:16d = int(invert(e,phi))17return n,e,d1819def calc(n,p,data):20num = bytes_to_long(data)21res = pow(num,p,n)22return long_to_bytes(res).encode('hex')2324def readFlag():25flag = open('flag').read()26assert len(flag) >= 5027assert len(flag) <= 6028prefix = os.urandom(68)29return prefix+flag3031if __name__ == '__main__':32n,e,d = genKey()33flag = calc(n,e,readFlag())34print 'Here is the flag!'35print flag36for i in xrange(150):37msg = raw_input('cmd: ')38if msg[0] == 'A':39m = raw_input('input: ')40try:41m = m.decode('hex')42print calc(n,e,m)43except:44print 'no'45exit(0)46elif msg[0] == 'B':47m = raw_input('input: ')48try:49m = m.decode('hex')50print calc(n,d,m)[-2:]51except:52print 'no'53exit(0)545556