Skip to content

Instantly share code, notes, and snippets.

@filiptronicek
Created September 28, 2023 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save filiptronicek/f7ba94a3ae10aa506a3d24714f2b68af to your computer and use it in GitHub Desktop.
Save filiptronicek/f7ba94a3ae10aa506a3d24714f2b68af to your computer and use it in GitHub Desktop.
Sample diffie-helman implementation in Python
# Importing necessary libraries
import random
# Function to compute the modular exponentiation (a^b mod p)
def mod_exp(a, b, p):
return pow(a, b, p)
def diffie_hellman(p, g):
# Alice chooses a private key
a = random.randint(1, p - 1)
# Alice computes her public key
A = mod_exp(g, a, p)
# Bob chooses a private key
b = random.randint(1, p - 1)
# Bob computes his public key
B = mod_exp(g, b, p)
# Alice and Bob exchange public keys and compute the shared secret
shared_secret_alice = mod_exp(B, a, p)
shared_secret_bob = mod_exp(A, b, p)
# Both shared secrets should be equal
assert shared_secret_alice == shared_secret_bob
return shared_secret_alice
p = 23
g = 5
# Running the Diffie-Hellman key exchange
shared_secret = diffie_hellman(p, g)
print(f'The shared secret is: {shared_secret}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment