Auties01
Auties01

Reputation: 54

Calculate Diffie-hellman key agreement using Curve25519 keys using the JCA

I'm generating two Curve25519 keypairs in Java 21 using the following code:

var kpg = KeyPairGenerator.getInstance("X25519");
var paramSpec = new NamedParameterSpec("X25519");
kpg.initialize(paramSpec);
var keyPair = kpg.generateKeyPair();

Now I'd like to calculate the key agreement(or shared secret) for the two key pairs using Ed25519:

var keyAgreement = KeyAgreement.getInstance("ECDH");
keyAgreement.init(privateKey);
keyAgreement.doPhase(publicKey, true);
var result = keyAgreement.generateSecret();

This obviously doesn't work as KeyAgreement only takes a KeyPair made up by a ECPublicKey and ECPrivateKey, not a XECPublicKey and XECPrivateKey. So what I need to do is convert the XECPublicKey into an ECPublicKey and the XECPrivateKey in an ECPrivateKey.

If I understand correctly, I can take the U point(encoded as a 32 bytes big endian big integer) of the XECPublicKey and compute the compressed affine y coordinate for the ECPublicKey with the following formula:

y = (u-1)/(u+1)

Which I would then need to decompress using the twisted Edwards point decompression algorithm(is it already implemented in Java?). Then from there I don't know how to get the affine x coordinate. Both should be 48 bytes long.

While for the private key, I'd have to compute the S coordinate(encoded as a 48 bytes long big endian Big integer) from the scalar component of the XECPrivateKey. I don't really know how to though.

Upvotes: 0

Views: 166

Answers (0)

Related Questions