Feb 26, 2025

Diffie-Hellman Key Exchange

Imitate and represent the exchange of keys between two "people".

Source Code

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

public class DiffieHellman {
    private BigInteger privateKey;
    private BigInteger publicKey;
    private BigInteger sharedSecret;
    private static final BigInteger g = new BigInteger("2"); // Generator
    private static final BigInteger p = new BigInteger("23"); // Prime number

    public DiffieHellman() {
        SecureRandom random = new SecureRandom();
        privateKey = new BigInteger(16, random);
        publicKey = g.modPow(privateKey, p);
    }

    public BigInteger getPublicKey() {
        return publicKey;
    }

    public void generateSharedSecret(BigInteger otherPublicKey) {
        sharedSecret = otherPublicKey.modPow(privateKey, p);
    }

    public BigInteger getSharedSecret() {
        return sharedSecret;
    }

    public static void main(String[] args) {
        DiffieHellman alice = new DiffieHellman();
        DiffieHellman bob = new DiffieHellman();

        // Exchange public keys
        alice.generateSharedSecret(bob.getPublicKey());
        bob.generateSharedSecret(alice.getPublicKey());

        System.out.println("Alice's Shared Secret: " + alice.getSharedSecret());
        System.out.println("Bob's Shared Secret: " + bob.getSharedSecret());
    }
}

Output

Alice's Shared Secret: 9
Bob's Shared Secret: 9