如何使用FIPS BouncyCastle将ECPrivateKey转换为ECPublicKey?
我使用以下代码(略有简化)将ECPrivateKey转换为ECPublicKey:
public static ECPublicKey getPublicKeyFromPrivateKey(ECPrivateKey privateKey) throws GeneralSecurityException {
final KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider());
final BCECPrivateKey bcecPrivateKey = (BCECPrivateKey) privateKey;
final ECParameterSpec ecSpec = bcecPrivateKey.getParameters();
final ECPoint q = ecSpec.getG().multiply(bcecPrivateKey.getD());
final byte[] qBytes = q.getEncoded(false);
final ECPoint point = ecSpec.getCurve().decodePoint(qBytes);
final ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, ecSpec);
return (ECPublicKey) keyFactory.generatePublic(pubSpec);
}
与非FIPS BouncyCastle配合使用时效果很好。现在,我们需要以符合FIPS的方式做同样的事情。这里的问题是FIPS BouncyCastle 1.0.1中似乎不存在ECParameterSpec之类的类。我们如何用FIPS BouncyCastle做同样的事情?
答案 0 :(得分:1)
我找到了适合我的以下解决方案:
public static PublicKey getPublicKeyForPrivateKeyEC(ECPrivateKey privateKey) throws GeneralSecurityException {
final KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider());
final ECParameterSpec ecSpec = privateKey.getParams();
final ECCurve ecCurve = FipsECUtil.convertCurve(ecSpec);
final ECMultiplier multiplier = ecCurve.getMultiplier();
final ECPoint generatorP = FipsECUtil.convertPoint(ecSpec, ecSpec.getGenerator());
final ECPoint q = multiplier.multiply(generatorP, privateKey.getS());
final byte[] publicDerBytes = q.getEncoded(false);
final ECPoint point = ecCurve.decodePoint(publicDerBytes);
final ECPublicKeySpec pubSpec = new ECPublicKeySpec(new java.security.spec.ECPoint(
point.getAffineXCoord().toBigInteger(),
point.getAffineYCoord().toBigInteger()), ecSpec);
return keyFactory.generatePublic(pubSpec);
}