I've just made my own implementation of Diffie Hellman in nodejs (its for a project of mine). However the shared keys are integers, I want to use those integers as a key to encrypt data. This is an example output:

Publicly Shared Variables:

    Publicly Shared Prime:  9811

    Publicly Shared Base:   844

Private Variables:

    Alice Secret:   6

    Bob Secret:   15

Alice Sends Over Public Chanel:  905

Bob Sends Over Public Chanel:  1168


Privately Calculated Shared Secret:

    Alice Shared Secret:  3793

    Bob Shared Secret:  3793

What would be the best encryption method, using the key of those integers. Sorry this is a bit hard to explain. Thanks alot!


What would be the best encryption method[...]?

The standard approach is quite simple. You have a Diffie-Hellman shared secret $K$. Because $K$ is not actually uniformly distributed you run $K$ through a key-based key derivation function (KBKDF) like HKDF (or even a "simple" hash), this is your key $k$ then. Then you use $k$ to symmetrically encrypt (and authenticate) data using a unique nonce for each data packet. You can also derive multiple different keys from the shared secret, e.g. one for each transmission direction.

You may want to note though that your current parameters are a bit on the insecure side being only 12-bit long as opposed to the current standard 2048-bit length.

  • 1
    $\begingroup$ You would need to encode the shared secret before using it as input for the KDF, preferably using I2OSP: an unsigned, big endian value with the same size as the key size. This is the default (and which is now integrated into TLS 1.3, as I proposed it for changeset 13). $\endgroup$ – Maarten Bodewes Aug 12 '18 at 22:16

So I found AES and decided to use that heres the functions (using the crypto module).

const crypto = require("crypto");

[...] // Rest of code

var encryptInformation = function(KEY, text){
  const cipher = crypto.createCipher('aes192', KEY);
  var encrypted = cipher.update(text,'utf8', 'hex');
  encrypted += cipher.final('hex');
  return encrypted;

var decryptInformation = function(KEY, text){
  const decipher = crypto.createDecipher('aes192', KEY)
  var decrypted = decipher.update(text,'hex','utf8')
  decrypted += decipher.final('utf8');
  return decrypted;

It works perfectly. However I don't know if it is the most secure, any better ideas?


Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.