Skip to content

Instantly share code, notes, and snippets.

@dvliman
Created June 26, 2019 04:29
Show Gist options
  • Save dvliman/dcbb311fc00f8c6260527adacef2c4ee to your computer and use it in GitHub Desktop.
Save dvliman/dcbb311fc00f8c6260527adacef2c4ee to your computer and use it in GitHub Desktop.
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator keygen = KeyPairGenerator.getInstance("ECDH", "BC");
keygen.initialize(ECNamedCurveTable.getParameterSpec("P-256"), new SecureRandom());
KeyPair keypair1 = keygen.generateKeyPair();
KeyPair keypair2 = keygen.generateKeyPair();
String secret1 = computeSecret((ECPrivateKey) keypair1.getPrivate(), (ECPublicKey) keypair2.getPublic());
String secret2 = computeSecret((ECPrivateKey) keypair2.getPrivate(), (ECPublicKey) keypair1.getPublic());
System.out.println(secret1);
System.out.println(secret2);
}
public static String computeSecret(ECPrivateKey privateKey, ECPublicKey publicKey) throws Exception {
KeyAgreement ka = KeyAgreement.getInstance("ECDH", "BC");
ka.init(privateKey);
ka.doPhase(publicKey, true); // true = lastPhase
return Base64.encodeBase64String(ka.generateSecret());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment