Thursday, September 15, 2016

How-To Diffie-Hellman key exchange in Java

Public key exchange is an interesting topic in the field of cryptography nowadays. Many sites and web services offer Perfect Forward Secrecy, protecting their users against future compromise of long-term keys. This protection is possible thanks to algorithms such as Diffie-Hellman (DH) and Elliptic Curve Diffie-Hellman (ECDH).

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.

No comments:

Post a Comment