Created
January 28, 2022 15:55
-
-
Save clarkmcc/308f1325d7375e4234826be9a95dca0c to your computer and use it in GitHub Desktop.
A naive and basic implementation of the Diffie-Hellman key exchange to more easily understand how the math works
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Diffie-Hellman asymetric key exchange allows two | |
// parties to cooperatively create a shared secret | |
// key without ever exchanging the shared secret. | |
// This means that it will be nearly impossible for | |
// a malicious party observing the creation of the | |
// shared secret to determine the secret key. | |
// Randomly create a generator number and a number p | |
// These two numbers are shared between both parties | |
// in the public space which means they're potentially | |
// accessible to a malicious party. I'm not following | |
// the Diffie-Hellman parameter requirements but the | |
// math still checks out. | |
let g = 10; | |
let p = 20; | |
// The two parties wanting to communicate should generate | |
// their own private keys. These keys are never exposed | |
// to the public space. These numbers can be generated | |
// randomly. | |
let privateAlice = 4; | |
let privateBob = 5; | |
// Each party computes it's own public key by taking the | |
// private key raised to the generator and applying modulo p. | |
let publicAlice = (privateAlice^g)%p; | |
let publicBob = (privateBob^g)%p; | |
// Each party exchanges public keys and then computes a | |
// shared key by raising the private key to the other | |
// party's public key and then applying modulu p. | |
// Mathematically this produces the same number and now | |
// both parties have a shared secret that was exchanged | |
// without ever exposing the secret in the public space. | |
let sharedAlice = (privateAlice^publicBob)%p; | |
let sharedBob = (privateBob^publicAlice)%p; | |
console.log(sharedAlice, sharedBob); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment