Skip to content

Instantly share code, notes, and snippets.

@protosam
Created September 8, 2017 01:51
Show Gist options
  • Save protosam/acea262af2e86adcb69a063f68ae32c4 to your computer and use it in GitHub Desktop.
Save protosam/acea262af2e86adcb69a063f68ae32c4 to your computer and use it in GitHub Desktop.
Example of the Diffee Hellman Key Exchange Algorithm with Annotations.
/* The Diffie Hellman Key Exchange - Explained Again, with code
-------------------------------------------------------------------------------
The Diffie Hellman Key Exchange is commonly explained like so:
Step 1. Alice and Bob agree on a large prime number "P" and a primitive root of that, "G"
Step 2. Alice and Bob choose a large random number to compute against "p" and "g"
Alice choses a large random number "x" creates "A" below to send Bob
A=G^x % P
Bob choses a large random number "y" creates "B" below to send Alice
B=G^y % P
Step 3. Alice and Bob exchange their results A and B to do the following.
Alice computes the following
k=B^x % P
Bob computes the following
k=A^y % P
Both Alice and Bob will end up with the same number (k) to use for cryptography stuff.
NOTE: Only CAPITALIZED variables are shared during this exchange.
................................................................................
Javascript Code Tutorial time!
Alice and Bob both agree to use the following SAFE_PRIME number and
PRIMITIVE_ROOT. NOTE: 23 is definitely not a safe prime these days. lol */
SAFE_PRIME = 23 // This is NOT a safe prime really...
PRIMITIVE_ROOT = 5 // 23's primitive roots, are 5, 7, 10, 11, 14, 15, 17, 19, 20, and 21.
/* Now Alice and Bob both choose a SECRET_NUMBER below and make a SAFE_DERIVITVE
of their choosen numbers.*/
SECRET_NUMBER_A = 6 // Alice chooses 6
SAFE_DERIVITIVE_A = Math.pow(PRIMITIVE_ROOT, SECRET_NUMBER_A) % SAFE_PRIME
SECRET_NUMBER_B = 15 // Bob chooses 15
SAFE_DERIVITIVE_B = Math.pow(PRIMITIVE_ROOT, SECRET_NUMBER_B) % SAFE_PRIME
/* Alice and Bob have given each other their SAVE_DERIVITIVEs and they will use
their SECRET_NUMBERs as a mixin to find a SHARED_SECRET */
ALICE_FINDS_SECRET = Math.pow(SAFE_DERIVITIVE_B, SECRET_NUMBER_A) % SAFE_PRIME
BOB_FINDS_SECRET = Math.pow(SAFE_DERIVITIVE_A, SECRET_NUMBER_B) % SAFE_PRIME
/* Both Alice and Bob now have the secret number 2. They can use it with some
form of shared encryption method that they both know to encode messages if they
would like to continue talking securely. */
console.log(ALICE_FINDS_SECRET)
console.log(BOB_FINDS_SECRET)
/* The Footnotes:
The following is shareable in public space without any worries:
SAFE_PRIME
PRIMITIVE_ROOT
SAFE_DERIVITIVE_A
SAFE_DERIVITIVE_B
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment