问题描述
我正试图在我的应用程序中生成一个共享机密,如下所示:
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();
}
这工作正常,但是我在这里使用的PublicKey
应该来自后端.
This is working fine, but the PublicKey
I use here should be coming from the backend.
后端只是向我发送椭圆曲线上某点的x
和y
值,现在我应该据此生成PublicKey
.但我只是想不通!如何仅从这两个值创建PublicKey
实例?
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?
推荐答案
实际上非常简单!但是除了x
和y
值之外,您还需要做其他事情.您还需要一个ECParameterSpec
! ECParameterSpec
描述您正在使用的椭圆曲线,您的应用必须使用与后端相同的ECParameterSpec
!
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!
使用x
和y
值可以创建ECPoint
实例,并且可以与ECParameterSpec
一起创建ECPublicKeySpec
:
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);
现在使用ECPublicKeySpec
,您可以使用KeyFactory
生成PublicKey
:
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.
这篇关于根据椭圆曲线点的x和y值生成PublicKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!