Requirement: For a given named-curve, send as little data as you can, so that receiver can construct EC PrivateKey.
I am currently using BouncyCastle/SpongyCastle on Android. This is what I have understood till now.
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));
Now, using Bouncy/Spongy castle, I get the actual point for the Private Key, without any other information which is present in derEncoding.
ECPrivateKeyParameters param = (ECPrivateKeyParameters) ECUtil.generatePrivateKeyParameter(privateKey);
int lenghtOfKey = param.getD().toByteArray().length; // length - 14
Question: How can I reconstruct PrivateKey object, just by using the point D (privateKeyParam.getD()
) and curve name? Using curve name, I can get ECCurveParameters.
Edit: I am able to construct ECPrivateKeyParameters
using private key point (praram.getD()
) but still couldn't figure out how to can I generate PrivateKey from ECPrivateKeyParameters
.
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);
I was able to figure out how to re-construct EC PrivateKey from BigInteger D & curve name.
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;
}
}