Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Cryptography Cryptography Tutorial Java Java and Cryptography Mastery Series Module 4 - Asymmetric Cryptography

Java Program for Diffie Hellman Key Exchange Algorithm

Reviewed & accurate
AI Summary

Introduction

The Diffie Hellman key exchange algorithm, published by Whitfield Diffie and Martin Hellman in their landmark 1976 paper "New Directions in Cryptography", was the first practical method for two strangers to agree on a shared secret over an open channel. The same idea was discovered independently by Malcolm Williamson at GCHQ in 1974 but kept classified. In this diffie hellman key exchange java tutorial we will implement the protocol from scratch using Java's BigInteger class, with no external libraries.

Before Diffie Hellman, two parties who wanted to communicate secretly had to meet in person to share a key. After Diffie Hellman, two parties could shake hands over the internet and agree on a shared secret even if every byte they exchanged was being recorded. The security rests on the hardness of the discrete logarithm problem in certain groups. Diffie Hellman is the foundation of TLS, SSH, IPsec, Signal's X3DH, and many other key agreement protocols.

What is Diffie Hellman?

Diffie Hellman is a key agreement protocol, not an encryption algorithm. It does not encrypt messages; it produces a shared secret that two parties can then feed into a symmetric cipher such as AES. The two parties start with public, agreed parameters: a large prime p and a generator g of a subgroup of integers modulo p. Each party then picks a private random value, computes a public value by raising g to that private value mod p, sends the public value to the other party, and finally raises the received public value to their own private value mod p. Both parties arrive at the same number.

An eavesdropper sees p, g, and the two public values, but to recover the shared secret they would need to solve the discrete logarithm problem: given g and g^x mod p, find x. For properly chosen parameters, this is intractable.

Compared to RSA, Diffie Hellman cannot encrypt arbitrary messages. Compared to symmetric key agreement via pre-shared keys, Diffie Hellman allows strangers to agree on a key without meeting. The protocol provides no authentication by itself, which means an active attacker who can intercept and relay messages can impersonate both parties. This is the famous man-in-the-middle attack. Real systems authenticate the public values with signatures or certificates.

How Diffie Hellman Works Step by Step

Let us walk through the algorithm with very small numbers. Pick p = 23 (a small prime) and g = 5 (a primitive root mod 23). Alice picks a = 6, Bob picks b = 15.

Step 1: Alice computes her public value A = g^a mod p = 5^6 mod 23 = 15625 mod 23 = 8. She sends A = 8 to Bob.

Step 2: Bob computes his public value B = g^b mod p = 5^15 mod 23 = 30517578125 mod 23 = 19. He sends B = 19 to Alice.

Step 3: Alice computes the shared secret as s = B^a mod p = 19^6 mod 23 = 47045881 mod 23 = 2.

Step 4: Bob computes the shared secret as s = A^b mod p = 8^15 mod 23 = 35184372088832 mod 23 = 2.

Step 5: Both parties now hold the same secret s = 2. An eavesdropper who saw p = 23, g = 5, A = 8, B = 19 cannot easily compute s without solving a discrete log.

Notice that the two computations are equal because g^(ab) mod p = (g^a)^b mod p = (g^b)^a mod p. This is the algebraic miracle at the heart of the protocol.

Java Program for Diffie Hellman Key Exchange Algorithm

import java.math.BigInteger;
import java.security.SecureRandom;

public class DiffieHellmanDemo {

    static class Party {
        BigInteger p, g, secret, publicKey;
        Party(BigInteger p, BigInteger g, int bits) {
            this.p = p;
            this.g = g;
            this.secret = new BigInteger(bits, new SecureRandom())
                              .mod(p.subtract(BigInteger.ONE))
                              .add(BigInteger.ONE);
            this.publicKey = g.modPow(secret, p);
        }
        BigInteger computeShared(BigInteger otherPublic) {
            return otherPublic.modPow(secret, p);
        }
    }

    public static void main(String[] args) {
        int primeBits = 512; // toy size; use 2048+ in production
        BigInteger p = BigInteger.probablePrime(primeBits, new SecureRandom());
        BigInteger g = new BigInteger("2");

        Party alice = new Party(p, g, 256);
        Party bob   = new Party(p, g, 256);

        System.out.println("Public prime p: " + p);
        System.out.println("Generator    g: " + g);
        System.out.println("Alice public : " + alice.publicKey);
        System.out.println("Bob public   : " + bob.publicKey);

        BigInteger aliceShared = alice.computeShared(bob.publicKey);
        BigInteger bobShared   = bob.computeShared(alice.publicKey);

        System.out.println("Alice shared : " + aliceShared);
        System.out.println("Bob shared   : " + bobShared);
        System.out.println("Secrets match: " + aliceShared.equals(bobShared));
    }
}

Code Explanation Line by Line

The Party inner class models one side of the exchange. Each party stores the public parameters p and g, a private secret, and a public value that they will transmit. The constructor picks a random secret of a given bit length using SecureRandom. We mod by p - 1 and add 1 to ensure the secret is in the range 1 to p - 1, which is the valid range for Diffie Hellman exponents.

The public value is g raised to the secret mod p. The BigInteger class provides modPow for exactly this purpose, and it uses the efficient square-and-multiply algorithm under the hood. Even a 2048-bit modPow takes only a few milliseconds.

The computeShared method takes the other party's public value and raises it to this party's secret mod p. Because (g^a)^b = (g^b)^a = g^(ab), both parties compute the same value despite never exchanging their private secrets.

The main method orchestrates a complete exchange. We generate a 512-bit toy prime with BigInteger.probablePrime, which uses Miller-Rabin primality testing. We use g = 2 as the generator, which is a common choice. We create two Party instances for Alice and Bob, give each the same p and g, and then have them exchange public values. Each computes the shared secret from the other's public value. The final println confirms that the two shared secrets are equal.

In a real protocol, Alice and Bob would also exchange signatures over their public values so that an attacker cannot substitute their own public values in transit. Without such authentication, Diffie Hellman is vulnerable to man-in-the-middle attacks.

Sample Input and Output

Public prime p: 134832... (large number)
Generator    g: 2
Alice public : 56231... (large number)
Bob public   : 91207... (large number)
Alice shared : 70429... (large number)
Bob shared   : 70429... (large number)
Secrets match: true

The exact values will differ every run because the prime and the secrets are freshly random. The crucial fact is the last line: the secrets match.

Common Mistakes to Avoid

First, never use unauthenticated Diffie Hellman in a real protocol. An active attacker can intercept Alice's public value, send their own public value to Bob, do the same in the other direction, and decrypt all traffic. Always authenticate the public values, for example by signing them with an RSA or Ed25519 key whose fingerprint is pre-shared.

Second, never reuse a private secret across multiple sessions. If your secret ever leaks, every past session key derived from that secret can be recovered. Generate a fresh secret for every session. This is called ephemeral Diffie Hellman, and it gives forward secrecy.

Third, never use a small prime. A 512-bit prime can be cracked in hours with special number-field-sieve hardware. Use a 2048-bit prime for short-term security and 3072 bits for long-term security.

Fourth, never use an arbitrary generator. The generator must produce a large prime-order subgroup of the multiplicative group mod p. Safe primes (p = 2q + 1 with q also prime) and generators of order q are the standard choice.

Real-World Applications

Diffie Hellman is the key agreement protocol in TLS 1.2 and TLS 1.3, where it is combined with digital signatures to authenticate the exchange. SSH supports Diffie Hellman groups for key agreement. Signal uses an extended triple-Diffie-Hellman protocol (X3DH) for asynchronous key agreement. VPN protocols such as IPsec use Diffie Hellman to establish session keys. The Bitcoin and Ethereum ecosystems use elliptic-curve Diffie Hellman, the same idea over a different group.

Conclusion

One technical point worth understanding: the security of Diffie Hellman depends not just on the size of the prime p but also on the structure of the group the protocol runs in. The multiplicative group of integers modulo p has order p-1, which has many small factors, and an attacker can use the Pohlig-Hellman algorithm to break the discrete log in stages by attacking each prime factor of p-1 separately. To resist this, the prime p must be a safe prime (p = 2q + 1 with q also prime) or have a known large prime factor q, and the generator g must produce a subgroup of order q. Using an arbitrary prime and an arbitrary generator is one of the most common real-world mistakes in deploying Diffie Hellman.

The elliptic-curve version of Diffie Hellman, called ECDH, offers the same protocol structure but works over the group of points on an elliptic curve. The advantage of ECDH is that the best known algorithm for the discrete logarithm problem in an elliptic-curve group takes roughly the square root of the group order, compared to roughly the cube root for integers modulo a prime. This means a 256-bit elliptic-curve group gives the same security as a 3072-bit prime-field group. ECDH is now the default key agreement algorithm in TLS 1.3 and Signal.

In this diffie hellman key exchange java tutorial we implemented the protocol from scratch, walked through every step of the math, and confirmed that two parties who never shared a secret can compute the same shared secret. The next step is to study elliptic-curve Diffie Hellman, which offers the same security with much smaller keys.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments