ECDH Key Agreement Secret
Derive a shared secret with javax.crypto.KeyAgreement over EC keys and verify that both sides compute identical bytes.
Code
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
HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.