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

Java/Android - ECDH Encryption - Create ECPublicKey from String

我对 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 编码我的 public 密钥:

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

这是收到的密钥示例:

keyPairA_public_base64 = "MFowFAYHKoZIzj0CAQYJKyQDAwIIAQEHA0IABGuSxmgwVGLHwcVhSf7C4/BfxfL4pGixHht8rWjPMBMTH5Vav1RQnf/Ucv9rLpD3M6ad8hHotwP5IpFsQT3hRkg="

现在,我需要使用 public 密钥(字符串)生成一个 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);

但是,我有一个错误:当我使用 ECPointUtil.decodePoint()[=15= 时,Invalid point encoding 0x30 ]

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

你能帮帮我吗? :)

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

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);