我想获得一个压缩的EC公钥表示,我按照这个答案来实现这一点。但是当我尝试将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);