TL;DR
This guide shows you how to set up a secure key exchange using Diffie-Hellman. It’s a way for two people to create a shared secret over an insecure connection, allowing them to encrypt messages without ever sending the secret itself directly.
Understanding Diffie Hellman
Diffie-Hellman isn’t about exchanging keys themselves; it’s about agreeing on a shared secret. Both parties generate their own private and public keys, exchange the public keys, and then use those to calculate the same shared secret. This is done mathematically without revealing either party’s private key.
Setting up Diffie Hellman
- Choose a Large Prime Number (p): This number needs to be very large for security – at least 2048 bits long. It’s publicly known.
# Example using OpenSSL (for demonstration - don't use this in production!) - Choose a Generator (g): This is another number that is less than p and greater than 1. It also needs to be publicly known.
# Example: g = 2 - Party A Generates Keys:
- Choose a private key (a) – this is kept secret!
- Calculate the public key (A): A = ga mod p
- Party B Generates Keys:
- Choose a private key (b) – this is kept secret!
- Calculate the public key (B): B = gb mod p
- Exchange Public Keys: Party A sends their public key (A) to Party B, and Party B sends their public key (B) to Party A. This exchange can happen over an insecure channel.
- Calculate the Shared Secret:
- Party A calculates the shared secret: s = Ba mod p
- Party B calculates the shared secret: s = Ab mod p
Both Party A and Party B will arrive at the same shared secret (s).
Example Calculation
Let’s use small numbers for simplicity. Do not use these in a real system!
- p = 23
- g = 5
Party A
- a = 6 (private key)
- A = 56 mod 23 = 8
Party B
- b = 15 (private key)
- B = 515 mod 23 = 19
Exchange Public Keys
A sends 8 to B, and B sends 19 to A.
Calculate Shared Secret
- Party A: s = 196 mod 23 = 2
- Party B: s = 815 mod 23 = 2
Both parties have the shared secret ‘2’.
Using the Shared Secret
The shared secret can now be used as a key for symmetric encryption algorithms like AES. It’s crucial to use a Key Derivation Function (KDF) to create strong keys from the shared secret.
Important Security Considerations
- Man-in-the-Middle Attack: Diffie-Hellman is vulnerable to man-in-the-middle attacks. Authentication is essential to verify the identity of the parties exchanging keys.
- Large Prime Number: Use a very large prime number (at least 2048 bits) for security.
- Key Derivation Function (KDF): Always use a KDF like HKDF or PBKDF2 to derive strong encryption keys from the shared secret.
- Elliptic Curve Diffie-Hellman (ECDH): ECDH is a more modern and efficient version of Diffie-Hellman that uses elliptic curves. It provides better security with smaller key sizes.