Path: blob/master/Public Key/RSA/common_modulus.py
336 views
import binascii1from fractions import gcd23def 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)910def modinv(a, m):11g, x, y = egcd(a, m)12if g != 1:13raise ValueError('Modular inverse does not exist.')14else:15return x % m1617def common_modulus(c1, c2, e1, e2, N):18if gcd(e1, e2) != 1:19raise ValueError("e1 and e2 must be coprime")20s1 = modinv(e1,e2)21s2 = (gcd(e1,e2) - e1 * s1) / e222temp = modinv(c2, N)23m1 = pow(c1,s1,N)24m2 = pow(temp,-s2,N)25return (m1 * m2) % N26#print((s1 * e1 + s2 * e2)%n)2728def test():29m = int("hello".encode("hex"),16)30n = 857459027535315046806654747618338111539888970464079862586251511836696921080917337595962439156822698450687899118944634822975226849713724868220458479270529931e1 = 732e2 = 1133m_recovered = common_modulus(pow(m,e1,n),pow(m,e2,n),e1,e2,n)34assert m_recovered == m35print("Success!")36return 03738test()394041