Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/crypton
Path: blob/master/RSA-encryption/Attack-Common-Modulus/exploit.py
1402 views
1
import gmpy2
2
from Crypto.Util.number import *
3
4
def egcd(a, b):
5
if (a == 0):
6
return (b, 0, 1)
7
else:
8
g, y, x = egcd(b % a, a)
9
return (g, x - (b // a) * y, y)
10
11
# Calculates a^{b} mod n when b is negative
12
def neg_pow(a, b, n):
13
assert b < 0
14
assert GCD(a, n) == 1
15
res = int(gmpy2.invert(a, n))
16
res = pow(res, b*(-1), n)
17
return res
18
19
# e1 --> Public Key exponent used to encrypt message m and get ciphertext c1
20
# e2 --> Public Key exponent used to encrypt message m and get ciphertext c2
21
# n --> Modulus
22
# The following attack works only when m^{GCD(e1, e2)} < n
23
def common_modulus(e1, e2, n, c1, c2):
24
g, a, b = egcd(e1, e2)
25
if a < 0:
26
c1 = neg_pow(c1, a, n)
27
else:
28
c1 = pow(c1, a, n)
29
if b < 0:
30
c2 = neg_pow(c2, b, n)
31
else:
32
c2 = pow(c2, b, n)
33
ct = c1*c2 % n
34
m = int(gmpy2.iroot(ct, g)[0])
35
return long_to_bytes(m)
36