I am writing a program in python that generates a public and private key pair. My code so far looks like this
def gcd(a,b):
while b != 0:
a, b = b, a % b
return(a)
pass
def inverse(a, b): # use extended euclidean algorithm to find inverse
x1, x2, x3 = 1, 0, a
y1, y2, y3 = 0, 1, b
while y3 != 0:
d = x3 // y3
y1, y2, y3, x1, x2, x3 = (x1 - d * y1), (x2 - d * y2), (x3 - d * y3), y1, y2, y3
return x1 % d
pass
def generate_key(a, b):
n = a * b
p = (a-1) * (b-1)
e = random.randrange(1,p)
g = gcd(e, p)
while g != 1:
e = randrange(1,p)
g = gcd(e,p)
d=inverse(e,p)
return ((e,n), (d,n))
pass
But when I run a test code it never completes and goes on running until I manually stop it. Any ideas why this might be happening?
The problem with your code is the implementation of gcd, the return shouldn't be inside the while because it will run only once and return, you have to do something like this:
def gcd(a,b):
while b != 0:
a, b = b, a % b
return(a)
I don't know if there are any more problems because you didn't provide de inverse function