I am taking a cyber security class recently. I was wondering if I was given two public keys, $n_1$ and $n_2$ (and $e$ the exponent)--how would one generate a private key for $n_1$? In this scenario, $n_1$ and $n_2$ share primes, namely $p$. $e$ is also same.
I know I need to use
$=^{−1} \mod (−1)(−1)$
and I also know since they share primes $(p)$, I could find their corresponding $q$ easily. However, I was stuck in calculating $d$.
def calculate_private_key(n1, n2, e):
# Step 1: Calculate the prime factor (p) shared by n1 and n2
p = gcd(n1, n2)
# Step 2: Calculate the remaining factors (q1 and q2)
q1 = n1 // p
q2 = n2 // p
# Step 3: Calculate the totient (phi) of the modulus (n)
phi1 = (p - 1) * (q1 - 1)
phi2 = (p - 1) * (q2 - 1)
# Step 4: Calculate the modular inverse
d1 = find_modular_inverse(e, phi1)
d2 = find_modular_inverse(e, phi2)
q1_inv = find_modular_inverse(q1, p)
q2_inv = find_modular_inverse(q2, p)
d = (d1 * q1 * q2_inv + d2 * q2 * q1_inv) % (p * q1 *q2)
return d
I assume CRT was needed to solve $d$ and this is what I wrote, but the answer was wrong. I was wondering where it went wrong. Any insights would be greatly appreciated. I was wondering did I implemented the top formula wrongly.
To be clearer, gcd/find_modular_inverse are self-defined function.
def gcd(a, b):
while b:
a, b = b, a % b
return a
def extended_euclidean(a, b):
if b == 0:
return a, 1, 0
else:
gcd, x, y = extended_euclidean(b, a % b)
return gcd, y, x - (a // b) * y
def find_modular_inverse(q2, p):
gcd, x, _ = extended_euclidean(p, q2)
if x < 0:
x += p
return x