Path: blob/master/RSA-encryption/Attack-Common-Modulus/exploit.py
1402 views
import gmpy21from Crypto.Util.number import *23def egcd(a, b):4if (a == 0):5return (b, 0, 1)6else:7g, y, x = egcd(b % a, a)8return (g, x - (b // a) * y, y)910# Calculates a^{b} mod n when b is negative11def neg_pow(a, b, n):12assert b < 013assert GCD(a, n) == 114res = int(gmpy2.invert(a, n))15res = pow(res, b*(-1), n)16return res1718# e1 --> Public Key exponent used to encrypt message m and get ciphertext c119# e2 --> Public Key exponent used to encrypt message m and get ciphertext c220# n --> Modulus21# The following attack works only when m^{GCD(e1, e2)} < n22def common_modulus(e1, e2, n, c1, c2):23g, a, b = egcd(e1, e2)24if a < 0:25c1 = neg_pow(c1, a, n)26else:27c1 = pow(c1, a, n)28if b < 0:29c2 = neg_pow(c2, b, n)30else:31c2 = pow(c2, b, n)32ct = c1*c2 % n33m = int(gmpy2.iroot(ct, g)[0])34return long_to_bytes(m)3536