I am using the java.security library to do an Elliptic Curve Digital Signature. I do not get a syntax error or any exception error.
The code basically creates a public and private key. I then test it by creating a signature of a string and I use the same string for verification. However, the result is false but it should be true.
I do not know where I am going wrong. Any feedback is appreciated.
The code as follows:
import java.security.*;
import java.security.spec.ECGenParameterSpec;
public class ECTests {
static PrivateKey privatekey;
static PublicKey publickey;
public static void main(String[] args) throws Exception {
generateKeyPair();
String strTest = "Hello World! This is a test";
byte[] sign = generateSignature(privatekey, strTest.getBytes());
boolean isSignValid = verifySignature(publickey, strTest.getBytes(), sign);
System.out.println(isSignValid);
}
public static KeyPair generateKeyPair() throws GeneralSecurityException {
KeyPairGenerator keyPair = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec ec = new ECGenParameterSpec("secp256r1");
keyPair.initialize(ec, new SecureRandom());
privatekey = keyPair.genKeyPair().getPrivate();
publickey = keyPair.genKeyPair().getPublic();
return keyPair.generateKeyPair();
}
public static byte[] generateSignature(PrivateKey ecPrivate, byte[] input) throws GeneralSecurityException {
Signature signature = Signature.getInstance("SHA256withECDSA");
signature.initSign(ecPrivate, new SecureRandom());
signature.update(input);
return signature.sign();
}
public static boolean verifySignature(PublicKey ecPublic, byte[] input, byte[] encSignature) throws GeneralSecurityException {
Signature signature = Signature.getInstance("SHA256withECDSA");
signature.initVerify(ecPublic);
signature.update(input);
boolean state = signature.verify(encSignature);
return state;
}
}