Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/crypton
Path: blob/master/RSA-encryption/Attack-Retrieve-Modulus/Challenges/Lost-Key/rsa.py
1402 views
1
#!/usr/bin/env python
2
from Crypto.Util.number import *
3
from gmpy2 import *
4
import os,sys
5
6
sys.stdin = os.fdopen(sys.stdin.fileno(), 'r', 0)
7
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
8
9
def genKey():
10
p = getPrime(512)
11
q = getPrime(512)
12
n = p*q
13
phi = (p-1)*(q-1)
14
while True:
15
e = getRandomInteger(40)
16
if gcd(e,phi) == 1:
17
d = int(invert(e,phi))
18
return n,e,d
19
20
def calc(n,p,data):
21
num = bytes_to_long(data)
22
res = pow(num,p,n)
23
return long_to_bytes(res).encode('hex')
24
25
def readFlag():
26
flag = open('flag').read()
27
assert len(flag) >= 50
28
assert len(flag) <= 60
29
prefix = os.urandom(68)
30
return prefix+flag
31
32
if __name__ == '__main__':
33
n,e,d = genKey()
34
flag = calc(n,e,readFlag())
35
print 'Here is the flag!'
36
print flag
37
for i in xrange(150):
38
msg = raw_input('cmd: ')
39
if msg[0] == 'A':
40
m = raw_input('input: ')
41
try:
42
m = m.decode('hex')
43
print calc(n,e,m)
44
except:
45
print 'no'
46
exit(0)
47
elif msg[0] == 'B':
48
m = raw_input('input: ')
49
try:
50
m = m.decode('hex')
51
print calc(n,d,m)[-2:]
52
except:
53
print 'no'
54
exit(0)
55
56