Diffie-Hellman Key Exchange


Diffie-Hellman key exchange allows two parties to generate a shared secret over an insecure channel.

You

Partner

Shared secret


Description

This tool will generate a key pair for you, of which you can send the public key to a partner. Once your partner sends you their public key, paste it into their public key box. If done successfully, you two should have an identical shared secret. You may use the shared secret to encrypt messages to each other, possibly by using the AES String Encryption and Decryption tool.

Do It Yourself

OpenSSL can help you perform a Diffie-Hellman key exchange, but it is not directly compatible with this tool. The principle, however, is the same.

During this process, we will need to generate 5 elements before deriving a shared secret:

  • A common base
  • Partner 1's private key
  • Partner 1's public key
  • Partner 2's private key
  • Partner 2's public key

Generate a Common Base

Use this command to generate a common base, dhp.pem. This DH Parameters key can be shared in a public manner between the two parties. It is not a secret. The library used by CryptoTools.net uses a constant value for its base.

$ openssl genpkey -genparam -algorithm DH -out dhp.pem

Partner 1's Key Pair

Partner 1 should be in possession of the dhp.pem file, then they can generate their private and public keys, dhpriv1.pem and dhpub1.pem, respectively.

$ openssl genpkey -paramfile dhp.pem -out dhpriv1.pem
$ openssl pkey -in dhpriv1.pem -pubout -out dhpub1.pem

Partner 2's Key Pair

Likewise, Partner 2 should be in posession of the same dhp.pem file and generate their own private and public keys.

$ openssl genpkey -paramfile dhp.pem -out dhpriv2.pem
$ openssl pkey -in dhpriv2.pem -pubout -out dhpub2.pem

Derive Shared Secret

Partner 1 should share dhpub1.pem with Partner 2, and Partner 2 should share dhpub2.pem with Partner 1. Once they have exchanged public keys, they may derive the shared secret. Partner 1's copy of the shared secret will be named shared1.bin, and Partner 2's will be named shared2.bin.

## Partner 1
$ openssl pkeyutl -derive -inkey dhpriv1.pem -peerkey dhpub2.pem -out shared1.bin
## Partner 2
$ openssl pkeyutl -derive -inkey dhpriv2.pem -peerkey dhpub1.pem -out shared2.bin

The content of files shared1.bin and shared2.bin should be exactly the same. Since they are binary files and not easily readable by humans, you may verify that they are the same like so:

$ sha256sum shared*.bin