Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/crypton
Path: blob/master/RSA-encryption/Intro-Challenges/Dp&Dq/encrypt.py
1402 views
1
from Crypto.Util.number import *
2
import gmpy2
3
from Crypto.PublicKey import RSA
4
from secret import flag, factor_p, factor_q
5
6
n = 78947048749078921553533397168223306327077414586183944609818553584663665747677757164091069731707888197818123265891690348381736231229561730395657333262905613958377739828118875586000068815867354664296956931106342366972209987312006882239420435532019823504851246162228112328268031305782869824549589268029030234941
7
e = 65537
8
9
p = factor_p
10
q = factor_q
11
assert p*q == n
12
phin = (p - 1)*(q - 1)
13
14
d = inverse(e, phin)
15
16
# d congruent to dp (mod p)
17
# d congruent to dq (mod q)
18
# Apply Chinese Remainder Theorem to solve the equations and get d
19
# Ref. to: https://crypto.stanford.edu/pbc/notes/numbertheory/crt.html
20
# Ref. to: https://en.wikipedia.org/wiki/Chinese_remainder_theorem
21
dp = d % (p-1)
22
dq = d % (q-1)
23
24
key = RSA.construct((n, long(e)))
25
obj1 = open("publickey.pem",'w')
26
obj1.write(key.exportKey('PEM'))
27
obj1.close()
28
29
message = bytes_to_long(flag)
30
ciphertext = pow(message, e, n)
31
ciphertext = long_to_bytes(ciphertext)
32
ciphertext = ciphertext.encode("hex")
33
34
f = open("data.txt",'w')
35
f.write("[*] ciphertext: " + ciphertext + "\n" + "[*] dp: " + str(dp) + "\n" + "[*] dq: " + str(dq))
36
f.close()
37