0% found this document useful (0 votes)
5 views1 page

DH

The document contains a Python script that generates a random prime number and finds a primitive root for it. It simulates a key exchange process between two parties, A and B, using the generated prime and primitive root to compute their private and public keys, as well as a shared secret. The script includes assertions to ensure the shared secrets computed by both parties are equal.

Uploaded by

mayurgbari52076
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views1 page

DH

The document contains a Python script that generates a random prime number and finds a primitive root for it. It simulates a key exchange process between two parties, A and B, using the generated prime and primitive root to compute their private and public keys, as well as a shared secret. The script includes assertions to ensure the shared secrets computed by both parties are equal.

Uploaded by

mayurgbari52076
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import random

def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True

def generate_prime():
while True:
num = random.randint(0, 100)
if is_prime(num):
return num

n = generate_prime()
print("Generated Prime (n):", n)

def find_primitive_root(n):
for g in range(2, n):
values = set()
for i in range(1, n):
values.add(pow(g, i, n)) # Compute g^i % n
if len(values) == n - 1: # If all numbers from 1 to n-1 are covered
return g
return None

g = find_primitive_root(n)
print("Primitive Root (g):", g)

# n = 19
# g = 7

a = random.randint(1, n-1) #Xa


A = (g ** a) % n

b = random.randint(1, n-1) #Xb


B = (g ** b) % n

secret_a = (B ** a) % n
secret_b = (A ** b) % n

print(f"A Private Key: {a}")


print(f"B Private Key: {b}")
print(f"A Public Key: {A}")
print(f"B Public Key: {B}")
print(f"A Shared Secret: {secret_a}")
print(f"B Shared Secret: {secret_b}")

assert secret_a == secret_b, "Key exchange failed!"

You might also like