You are on page 1of 1

1 # p and q have to be distinct primes

2 def rsa(p, q):


3
4 n = p * q
5 phi_n = (p - 1) * (q - 1)
6
7 e = 1
8 i = 0
9
10 # returns the public key (e, n)
11 while (i != 1):
12
13 e += 1
14 i = euclid(e, phi_n)
15
16 # returns the private key d
17 d = extended_euclid(e, phi_n)
18
19 # only the standard euclidean algorithm is necessary for the public key
20 def euclid(a, b):
21
22 while (b > 0):
23
24 r = a % b
25 a = b
26 b = r
27
28 return a
29
30 # only the x variables are necessary for the private key
31 def extended_euclid(a, b):
32
33 x = 1
34 x1 = 0
35 x2 = 1
36
37 while b > 0:
38
39 q = a // b
40 r = a % b
41
42 x = x2 - q * x1
43
44 a = b
45 b = r
46
47 x2 = x1
48 x1 = x
49
50 return x2
51
52 # encryption: c = m^e mod n
53 # decryption: m = c^d mod n
54
55 # Zn = {0 … (n - 1)}
56 # Zn* = {a | GCD(a, n) == 1, a >= 0, a < n}

You might also like