Java/Android - ECDH加密-从字符串中创建ECPublicKey



我对ECDH(椭圆曲线Diffie-Hellman)加密有一点问题。我使用BouncyCastle库。

下面是我生成密钥的函数:

public static KeyPair generateECKeys() {
try {
ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec("brainpoolp256r1");
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDH", "BC");
keyPairGenerator.initialize(parameterSpec);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
return keyPair;
} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | NoSuchProviderException e) {
Log.d("Error - ",e.getMessage());
e.printStackTrace();
return null;
}
}

我用base64编码我的公钥:

String keyPairA_public_base64 = Base64.getEncoder().encodeToString(keyPairA.getPublic().getEncoded());

下面是收到的密钥示例:

keyPairA_public_base64 = "MFowFAYHKoZIzj0CAQYJKyQDAwIIAQEHA0IABGuSxmgwVGLHwcVhSf7C4/BfxfL4pGixHht8rWjPMBMTH5Vav1RQnf/Ucv9rLpD3M6ad8hHotwP5IpFsQT3hRkg="

现在,我需要用公钥(String)生成一个ECPublicKey对象。

ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("brainpoolp256r1");
KeyFactory kf = KeyFactory.getInstance("ECDH", new BouncyCastleProvider());
ECNamedCurveSpec params = new ECNamedCurveSpec("brainpoolp256r1", spec.getCurve(), spec.getG(), spec.getN());
ECPoint point =  ECPointUtil.decodePoint(params.getCurve(), keyPairA.getPublic().getEncoded()); // Error here : Invalid point encoding 0x30
ECPublicKeySpec pubKeySpec = new java.security.spec.ECPublicKeySpec(point, params);
ECPublicKey pk = (ECPublicKey) kf.generatePublic(pubKeySpec);

但是,我有一个错误:无效点编码0x30当我使用ECPointUtil.decodePoint()

我不明白如何解决这个错误,如果我使用正确的方法从字符串创建一个ECPublicKey对象。

你能帮我一下吗?:)

ECPointUtil.decodePoint()需要一个原始公钥。另一方面,keyPairA_public_base64是一个Base64编码的X.509/SPKI格式的公钥(即不是原始公钥),可以按以下方式导入:

import java.security.spec.X509EncodedKeySpec;
import java.security.interfaces.ECPublicKey;
import java.security.KeyFactory;
...
X509EncodedKeySpec x509EncodedKeySpecA = new X509EncodedKeySpec(Base64.getDecoder().decode(keyPairA_public_base64));
KeyFactory keyFactoryA = KeyFactory.getInstance("ECDH");
ECPublicKey publicKeyA = (ECPublicKey)keyFactoryA.generatePublic(x509EncodedKeySpecA);

相关内容

  • 没有找到相关文章

最新更新