要求:对于给定的命名曲线,发送尽可能少的数据,以便接收方可以构造EC PrivateKey
我目前在Android上使用BouncyCastle/海绵城堡。这是我到目前为止所理解的。
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("secp112r2");
keyGen.initialize(ecGenParameterSpec, new SecureRandom());
KeyPair keyPair = keyGen.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
// privateKey.getEncoded() -> gives DER encoded private key. I can construct PrivateKey from that easily
byte[] derEncodedPrivateKeyBytes = privateKey.getEncoded(); // byteArray length-> 80
KeyFactory kf = KeyFactory.getInstance("EC");
PrivateKey key = kf.generatePrivate(new PKCS8EncodedKeySpec(derEncodedPrivateKeyBytes));
现在,使用Bouncy/sponge城堡,我得到了私钥的实际点,而没有derEncoding中存在的任何其他信息。
ECPrivateKeyParameters param = (ECPrivateKeyParameters) ECUtil.generatePrivateKeyParameter(privateKey);
int lenghtOfKey = param.getD().toByteArray().length; // length - 14
问题:如何通过点D (privateKeyParam.getD()
)和曲线名称来重建PrivateKey对象?使用曲线名称,我可以得到ECCurveParameters.
编辑:我能够使用私钥点(praram.getD()
)构建ECPrivateKeyParameters
,但仍然无法弄清楚如何从ECPrivateKeyParameters
生成PrivateKey。
X9ECParameters ecCurve = ECNamedCurveTable.getByName(curveName);
ECDomainParameters ecDomainParam = new ECDomainParameters(ecCurve.getCurve(),
ecCurve.getG(), ecCurve.getN(), ecCurve.getH(), ecCurve.getSeed());
ECPrivateKeyParameters generatedECPrivateKeyParams = new ECPrivateKeyParameters(param.getD(), ecDomainParam);
我能够弄清楚如何从BigInteger D &曲线的名字。
public static PrivateKey getPrivateKeyFromECBigIntAndCurve(BigInteger s, String curveName) {
X9ECParameters ecCurve = ECNamedCurveTable.getByName(curveName);
ECParameterSpec ecParameterSpec = new ECNamedCurveSpec(curveName, ecCurve.getCurve(), ecCurve.getG(), ecCurve.getN(), ecCurve.getH(), ecCurve.getSeed());
ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(s, ecParameterSpec);
try {
KeyFactory keyFactory = KeyFactory.getInstance("EC");
return keyFactory.generatePrivate(privateKeySpec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
return null;
}
}