#!/usr/local/cpython-3.6/bin/python
"""Illustrate how Diffie-Helman key exchange works."""
import random
P = 99999989
A = 11
def main() -> None:
"""Do the stuff :)."""
# local picks random ra, remote picks random rb
r_a = int(random.random() * P)
r_b = int(random.random() * P)
print(r_a, r_b)
# local computes ya, remote computes yb
y_a = pow(A, r_a, P)
print(y_a)
y_b = pow(A, r_b, P)
print(y_b)
# local and remote exchange ya and yb over the insecure channel
# local computes key, remote computes key
print('These two numbers should be the same:')
localkey = pow(y_b, r_a, P)
print(localkey)
remotekey = pow(y_a, r_b, P)
print(remotekey)
main()
#
# -----BEGIN PGP SIGNED MESSAGE-----
#
# Earlier somebody (Samuel Pigg?) asked for a D-H key exchange reference.
# It should be in any modern crypto textbook, and is easy to follow.
#
# Alice and Bob want to exchange keys over a hostile channel. They pick
# a prime p, a random number a, and exchange this information.
#
# Alice picks Ra, a random number less than p, and keeps it secret. Bob picks
# Rb, also a random number less than p. Alice calculates Ya = a^Ra mod p, and
# sends the result to Bob. Bob calculates Yb = a^Rb mod p, and sends the
# result to Alice. To recover the common key Alice and Bob will now use with
# each other, they raise the result the other person sent them to their secret
# random number, and take the result modulo p. That is, Alice calculates
# Yb^Ra mod p, and Bob calculates Ya^Rb mod p.
#
# Even if an eavesdropper gets a, p, and the intermediate Ya and Yb, the final
# key cannot be determined (due the difficulty of the discrete logarithm).
#
# Example:
#
# 1) Alice and Bob pick a = 11, p = 347
#
# 2) Alice picks Ra = 240
# Bob picks Rb = 39
#
# Alice and Bob keep Ra and Rb secret
#
# 3) Alice calculates Ya = a^Ra mod p
# = 11^240 mod 347 = 49
#
# Bob calculates Yb = a^Rb mod p
# = 11^39 mod 347 = 285
#
# 4) Alice sends Bob Ya = 49
# Bob sends Alice Yb = 285
#
#
# 5) Alice calculates Yb^Ra mod p = 285^240 mod 347
# = 268
#
# Bob calculates Ya^Rb mod p = 49^39 mod 347
# = 268
#
# Now Alice and Bob can communicate using their common key. Even if an
# enemy intercepts a = 11, p = 347, Ya = 49, and Yb = 285, the common
# key cannot be calcuated. (Well, they can here since I'm using small
# numbers, but with large numbers the discrete log problem is intractable).
#
#
# Karl Barrus
#
# -----BEGIN PGP SIGNATURE-----
# Version: 2.3a
#
# iQCVAgUBLJnEGYOA7OpLWtYzAQGbHwQAj91N509z07y5x7+ZB/bJnByjXbsQwKVI
# sCEidNzzo/f49q+z7D5ZiAhorrx/2BYk14kEcctGrbOMM72+2M8qOtOkQFf/YfQX
# Da48/pabZitC6pb91Xqjqd1Na6Ixz8PdKwXCDBUEphZSLzKOaEF24RXdKJfzhl88
# IRjhFXTUybA=
# =HNo8
# -----END PGP SIGNATURE-----