com.akeyless.crypto.ecdsa.ECDSAUtils Maven / Gradle / Ivy
package com.akeyless.crypto.ecdsa;
import org.bouncycastle.asn1.x9.ECNamedCurveTable;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECNamedCurveSpec;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPrivateKeySpec;
import java.security.spec.InvalidKeySpecException;
public class ECDSAUtils {
public static KeyPair generateKeyPair(String curveName)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
X9ECParameters ecCurve = ECNamedCurveTable.getByName(curveName);
ECParameterSpec ecParameterSpec = new ECNamedCurveSpec(curveName, ecCurve.getCurve(),
ecCurve.getG(), ecCurve.getN(), ecCurve.getH(), ecCurve.getSeed());
KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", new BouncyCastleProvider());
g.initialize(ecParameterSpec, new SecureRandom());
return g.generateKeyPair();
}
public static byte[] sign(String stringToSign, byte[] prvKeySeed, String curveName)
throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, InvalidKeySpecException {
BigInteger seed = new BigInteger(1, prvKeySeed);
PrivateKey prv = getPrivateKeyFromECBigIntAndCurve(seed, curveName);
Signature dsa = Signature.getInstance("SHA256withECDSA", new BouncyCastleProvider());
dsa.initSign(prv);
byte[] strByte = stringToSign.getBytes();
dsa.update(strByte);
return dsa.sign();
}
private static PrivateKey getPrivateKeyFromECBigIntAndCurve(BigInteger s, String curveName)
throws NoSuchAlgorithmException, InvalidKeySpecException {
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);
KeyFactory keyFactory = KeyFactory.getInstance("EC");
return keyFactory.generatePrivate(privateKeySpec);
}
}