Search code examples
javacryptographybouncycastlediffie-hellman

Using elliptic curve Diffie-Hellman with cofactor key for generating symmetric key


I am new to ECDH and wanted to generate the a secret key in Java. I wanted to use Elliptic curve Diffie-Hellman with cofactor key derivation. I'm using the P-256 curve for the elliptic curve operations. I'm planning to use the resulting secret as the symmetric key for my block cipher.

I have been working on this, and have the below working sample. This generates the secret key.

Provider BC = new org.bouncycastle.jce.provider.BouncyCastleProvider();
ProviderList.newList(BC);
ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-256");   
KeyPairGenerator g = (KeyPairGenerator) KeyPairGenerator.getInstance(
            "ECDH",BC);
g.initialize(ecSpec, new SecureRandom());

KeyPair aKeyPair = g.generateKeyPair();

KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDH", BC);

aKeyAgree.init(aKeyPair.getPrivate());

KeyPair bKeyPair = g.generateKeyPair();

KeyAgreement bKeyAgree = KeyAgreement.getInstance("ECDH", BC);

bKeyAgree.init(bKeyPair.getPrivate());

aKeyAgree.doPhase(bKeyPair.getPublic(), true);
bKeyAgree.doPhase(aKeyPair.getPublic(), true);

byte[] aSecret = aKeyAgree.generateSecret();
byte[] bSecret = bKeyAgree.generateSecret();

System.out.println(new String(aSecret));
System.out.println(new String(bSecret));

I am afraid that I am using an ephemeral private and public key instead of static keys. Please tell me how I can generate the secret key using a static private and public key.


Solution

  • You make static keys by simply storing them instead of generating them each time. You may have to use ECDHCBasicAgreement (note the additional C) to perform cofactor multiplication.

    Note that you should perform a KBKDF over the secret to generate symmetric keys.