I'm importing RSA key from a folder and using it to generate signature. but its giving me following error.
Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid parse error, not a sequence
following is the code for generating signature
public class GenerateSignature {
public String getSignature(String msg) {
HexString hs = new HexString();
byte[] signature = null;
try {
PrivateKeyLoader loader = new PrivateKeyLoader();
//put pertinent address
PrivateKey key = loader.load("rsakey2.pem");
System.out.println(key);
Signature sign = Signature.getInstance("SHA256withRSA");
sign.initSign(key);
byte[] bytes = msg.getBytes();
sign.update(bytes);
signature = sign.sign();
}
catch (Exception e) {
System.out.println(e); // this is where i got the error
//i think loader.load wasnt able to load the key.
}
return hs.toHexString(signature);
}
}
following is the code for loading private key
public class PrivateKeyLoader {
private String readFile(final String fileName) throws IOException {
final File file = new File(fileName);
return new String(Files.readAllBytes(file.toPath()));
}
private PrivateKey loadPemRsaPrivateKey(String pemFilename) throws Exception {
String pemString = readFile(pemFilename);
String privateKeyPEM = pemString
.replace("-----BEGIN RSA PRIVATE KEY-----", "")
.replaceAll(System.lineSeparator(), "")
.replace("-----END RSA PRIVATE KEY-----", "");
byte[] encoded = Base64.getDecoder().decode(privateKeyPEM);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
return keyFactory.generatePrivate(keySpec);
}
public PrivateKey load(String file) throws Exception {
return loadPemRsaPrivateKey(file);
}
}