I am trying to generate a shared secret in my app like this:
public static byte[] generateSharedSecret(PrivateKey privateKey PublicKey publicKey) {
KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH", "SC");
keyAgreement.init(privateKey);
keyAgreement.doPhase(publicKey, true);
return keyAgreement.generateSecret();
}
This is working fine, but the PublicKey
I use here should be coming from the backend.
The backend just sends me the x
and y
value of a point on an elliptic curve and now I am supposed to generate the PublicKey
from that. But I just can't figure it out! How can I create a PublicKey
instance just from those two values?
It's actually quite simple! But you need one more thing besides the
x
andy
values. You also need anECParameterSpec
! TheECParameterSpec
describes the elliptic curve you are using and your app has to use the sameECParameterSpec
as your backend does!With the
x
andy
values you can create anECPoint
instance and together with yourECParameterSpec
you can create anECPublicKeySpec
:And now with that
ECPublicKeySpec
you can generate thePublicKey
using aKeyFactory
:You can find more information about this topic here.