Implementing these techniques in your Java application is not the most straightforward thing to do. Luckily, the library that I used in my past article How-To encrypt a file in Java has convenient classes that greatly simplify the job. A shared secret can therefore be exchanged using Diffie-Hellman in just a few lines of code:
// Tip: You don't need to regenerate p; Use a fixed value in your application int bits = 2048; BigInteger p = BigInteger.probablePrime(bits, new SecureRandom()); BigInteger g = new BigInteger("2"); // Create two peers KeyAgreementPeer peerA = new DHPeer(p, g); KeyAgreementPeer peerB = new DHPeer(p, g); // Exchange public keys and compute shared secret byte[] sharedSecretA = peerA.computeSharedSecret(peerB.getPublicKey()); byte[] sharedSecretB = peerB.computeSharedSecret(peerA.getPublicKey());
Note: The p and g values here are not necessarily representative for production use. Use precomputed primes in order to be safe. A good starting point would be https://tools.ietf.org/html/rfc3526.
Performing a public key exchange using the Elliptic Curve Diffie-Hellman (ECDH) algorithm is done slightly different:
String algorithm = "brainpoolp512r1"; // Create two peers KeyAgreementPeer peerA = new ECDHPeer(algorithm); KeyAgreementPeer peerB = new ECDHPeer(algorithm); // Exchange public keys and compute shared secret byte[] sharedSecretA = peerA.computeSharedSecret(peerB.getPublicKey()); byte[] sharedSecretB = peerB.computeSharedSecret(peerA.getPublicKey());The ECDH peer class requires Bouncy Castle in order to work. Luckily this is already an import in the Encryptor4j project's build.gradle file.
Find out which elliptic curves are supported by Bouncy Castle here.