Blog | G5 Cyber Security

Diffie Hellman Key Exchange: A Secure Setup

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

  1. 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!)
  2. 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
  3. Party A Generates Keys:
    • Choose a private key (a) – this is kept secret!
    • Calculate the public key (A): A = ga mod p
  4. Party B Generates Keys:
    • Choose a private key (b) – this is kept secret!
    • Calculate the public key (B): B = gb mod p
  5. 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.
  6. 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!

Party A

Party B

Exchange Public Keys

A sends 8 to B, and B sends 19 to A.

Calculate Shared Secret

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

Exit mobile version