无法将 ECPublicKeyImpl 转换为 BCECPublicKey

Can't cast ECPublicKeyImpl to BCECPublicKey

我想要一个压缩的 EC public 密钥表示,我按照 的回答做到了这一点。 但是当我尝试将 java.security.PublicKey 转换为 org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey 时,出现异常:

jdk.crypto.ec/sun.security.ec.ECPublicKeyImpl cannot be cast to org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey

进口:

import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.math.ec.ECPoint;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.spec.ECGenParameterSpec;

代码:

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256k1");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
keyGen.initialize(ecSpec, random);
KeyPair pair = keyGen.generateKeyPair();

ECPoint ecPoint = ((BCECPublicKey) pair.getPublic()).getQ(); - Exception

System.out.println(new String(ecPoint.getEncoded(true)));

KeyPairGenerator.getInstance(String) 为您提供第一个实现给定算法的安全提供程序。如果没有进一步配置,它是 "SunEC".

由于您显然希望依靠 BouncyCastle 来生成您的密钥,因此请使用 2 参数工厂方法:

final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);

但是,如果您要接收 KeyPair 对象作为参数,您不能假设它来自 BouncyCastle,您应该手动将其转换为 BCECPublicKey,如 Topaco 的评论:

final BCECPublicKey pubKey = pair.getPublic() instanceof BCECPublicKey
  ? (BCECPublicKey) pair.getPublic()
  : new BCECPublicKey((ECPublicKey) pair.getPublic(), BouncyCastleProvider.CONFIGURATION);