Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

android - Generating PublicKey from x and y values of elliptic curve point

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's actually quite simple! But you need one more thing besides the x and y values. You also need an ECParameterSpec! The ECParameterSpec describes the elliptic curve you are using and your app has to use the same ECParameterSpec as your backend does!


With the x and y values you can create an ECPoint instance and together with your ECParameterSpec you can create an ECPublicKeySpec:

ECParameterSpec ecParameters = ...;
BigInteger x = ...;
BigInteger y = ...;

ECPoint ecPoint = new ECPoint(x, y);
ECPublicKeySpec keySpec = new ECPublicKeySpec(ecPoint, ecParameters);

And now with that ECPublicKeySpec you can generate the PublicKey using a KeyFactory:

KeyFactory keyFactory = KeyFactory.getInstance("EC");
PublicKey publicKey = keyFactory.generatePublic(keySpec);

You can find more information about this topic here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...