11from __future__ import annotations
22
33
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 ):
623 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 )
926 if val in li :
1027 break
1128 li .append (val )
@@ -15,18 +32,22 @@ def find_primitive(n: int) -> int | None:
1532
1633
1734if __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} " )
2243 else :
2344 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 )
2546 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 )
2748
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 )
3051
3152 print ("The key value generated by A is: " , a_secret )
3253 print ("The key value generated by B is: " , b_secret )
0 commit comments