justin.m.chase
justin.m.chase

Reputation: 13685

How do I actually encrypt something with the Diffie-Hellman apis in nodejs?

I'm looking at the very simple demo in the nodejs crypto documentation here: https://nodejs.org/api/crypto.html#crypto_crypto_getdiffiehellman_group_name

They very easily demonstrate how to get a shared secret... now what?

How can I use said shared secret to encrypt and decrypt data?

Upvotes: 4

Views: 6946

Answers (2)

argentum47
argentum47

Reputation: 2382

Although the question is how to encrypt with DH apis. I want to address the whole problem.

Although the accepted answer is good, but the problem is if you don't know how e2e works that tutorial won't help you to achieve what you actually want, which I guess is how to do end-to-end encryption using DH key exchange as a part of the process. So I broke it up into understand-able pieces.

It goes like this:

As the concept goes, both Alice and Bob should agree on a generator and a prime number to bob, so that key can generate his keys. Having done that, both of them need to share their public keys with each other.

So at first, let alice generate the keys and send them to bob:

JSON.stringify({ type: 'keyxchange_alice', from: from, to: to, prime: alice.sharedPrime, generator: alice.generator, key: alice.getPublicKey() })

And then bob will need to generate and send his public key to alice

  const bob = new DeffMan(Buffer.from(msg.prime), Buffer.from(msg.generator))
  const bob_key = bob.getPublicKey()
  JSON.stringify({ type: 'keyxchange_bob', key: bob_key })

Also you will need to store these keys corresponding users, which could be done by storing it (in this case, in a javascript hash/object), like alice can store: { bob: bobMessage.key }.

Now given that they have each other's public keys, alice can bob can generate a shared secret, shared secret, for bob, when generalized is alicePublicKey ^ bobPrivateKey. (read more on DiffeHelman key exchange from Wikipedia and a Plain English version here )

This shared secret then will use as a password to encrypt the messages using aes-256-cbc that will be send over tcp.

The above thing can be modified more, by regenerating the secret's everytime, which will involve one more roundrtrip for each message Or One could use the Double-Rachet scheme.

My original article is in this link as a gist

Upvotes: 3

ralh
ralh

Reputation: 2574

Diffie-Hellman is a key exchange algorithm. It does not provide encryption by itself.

After both parties have established a common secret through D-H, you can use that as a key in a symmetrical encryption algorithm like AES.

The secret can be used for example as a password for https://nodejs.org/api/crypto.html#crypto_crypto_createcipher_algorithm_password

Mind the security note at the end.

Upvotes: 10

Related Questions