ECDH Key Agreement Secret

Derive a shared secret with javax.crypto.KeyAgreement over EC keys and verify that both sides compute identical bytes.

JavaSecurity Boundaries

Code

snippet
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.spec.ECGenParameterSpec;
import java.util.Arrays;
import javax.crypto.KeyAgreement;

public class Main {
    public static void main(String[] args) throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
        generator.initialize(new ECGenParameterSpec("secp256r1"));

        KeyPair alice = generator.generateKeyPair();
        KeyPair bob = generator.generateKeyPair();

        // ECDH mixes each private key with the peer public key
        byte[] aliceSecret = agree(alice, bob.getPublic());
        byte[] bobSecret = agree(bob, alice.getPublic());
        System.out.println("alice secret bytes: " + aliceSecret.length);
        System.out.println("same secret: " + Arrays.equals(aliceSecret, bobSecret));

        // a third party with a different private key gets another value
        KeyPair eve = generator.generateKeyPair();
        byte[] eveSecret = agree(eve, alice.getPublic());
        System.out.println("eve differs: " + !Arrays.equals(aliceSecret, eveSecret));
    }

    private static byte[] agree(KeyPair own, PublicKey peer) throws Exception {
        KeyAgreement agreement = KeyAgreement.getInstance("ECDH");
        agreement.init(own.getPrivate());
        agreement.doPhase(peer, true);
        return agreement.generateSecret();
    }
}

How it works

The code’s whole job belongs to the class Main.

Caveats

  • No dependencies section needed; the standard library is the whole story.

Using it

Output lines are prefixed (alice secret bytes:, same secret:, eve differs:), so the printed lines and the steps that caused them stay paired.

Key statements

return agreement.generateSecret();

Interactive Tools for This Topic

FAQ

What does ECDH Key Agreement Secret print when run?
Running the file directly is enough — expect labeled output lines such as `alice secret bytes:`, `same secret:`, `eve differs:`.