I am trying to sign a string message using a private key that I had generated using the commands from here. This is the piece of code below that I use to load and sign the message.
private String signMessage(String message) throws Exception {
Signature rsa = Signature.getInstance("SHA1withRSA");
rsa.initSign(getPrivate(privateKeyPath));
rsa.update(message.getBytes());
return rsa.sign().toString();
}
public PrivateKey getPrivate(String filename) throws Exception {
byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
To clarify the privatekeyPath I am supplying is similar to /path/test.der
.
However, I am getting the following error when trying to sign the message - java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
What is wrong here? Why cant I seem to sign a message with the private key? Can someone specify a working way to get this done?