1
1
from __future__ import annotations
2
2
3
3
4
- def find_primitive (n : int ) -> int | None :
5
- for r in range (1 , n ):
4
+ def find_primitive (modulus : int ) -> int | None :
5
+ """
6
+ Find a primitive root modulo modulus, if one exists.
7
+
8
+ Args:
9
+ modulus : The modulus for which to find a primitive root.
10
+
11
+ Returns:
12
+ The primitive root if one exists, or None if there is none.
13
+
14
+ Examples:
15
+ >>> find_primitive(7) # Modulo 7 has primitive root 3
16
+ 3
17
+ >>> find_primitive(11) # Modulo 11 has primitive root 2
18
+ 2
19
+ >>> find_primitive(8) == None # Modulo 8 has no primitive root
20
+ True
21
+ """
22
+ for r in range (1 , modulus ):
6
23
li = []
7
- for x in range (n - 1 ):
8
- val = pow (r , x , n )
24
+ for x in range (modulus - 1 ):
25
+ val = pow (r , x , modulus )
9
26
if val in li :
10
27
break
11
28
li .append (val )
@@ -15,18 +32,22 @@ def find_primitive(n: int) -> int | None:
15
32
16
33
17
34
if __name__ == "__main__" :
18
- q = int (input ("Enter a prime number q: " ))
19
- a = find_primitive (q )
20
- if a is None :
21
- print (f"Cannot find the primitive for the value: { a !r} " )
35
+ import doctest
36
+
37
+ doctest .testmod ()
38
+
39
+ prime = int (input ("Enter a prime number q: " ))
40
+ primitive_root = find_primitive (prime )
41
+ if primitive_root is None :
42
+ print (f"Cannot find the primitive for the value: { primitive_root !r} " )
22
43
else :
23
44
a_private = int (input ("Enter private key of A: " ))
24
- a_public = pow (a , a_private , q )
45
+ a_public = pow (primitive_root , a_private , prime )
25
46
b_private = int (input ("Enter private key of B: " ))
26
- b_public = pow (a , b_private , q )
47
+ b_public = pow (primitive_root , b_private , prime )
27
48
28
- a_secret = pow (b_public , a_private , q )
29
- b_secret = pow (a_public , b_private , q )
49
+ a_secret = pow (b_public , a_private , prime )
50
+ b_secret = pow (a_public , b_private , prime )
30
51
31
52
print ("The key value generated by A is: " , a_secret )
32
53
print ("The key value generated by B is: " , b_secret )
0 commit comments