Reputation: 18760
When trying to read a RSA private key from a file using the method
public PrivateKey getPrivateKey()
throws NoSuchAlgorithmException,
InvalidKeySpecException, IOException {
final InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream("privatekey");
byte[] privKeyBytes = null;
try {
privKeyBytes = IOUtils.toByteArray(inputStream);
} catch (final IOException exception) {
LOGGER.error("", exception);
IOUtils.closeQuietly(inputStream);
}
LOGGER.debug("privKeyBytes: {}", privKeyBytes);
String BEGIN = "-----BEGIN RSA PRIVATE KEY-----";
String END = "-----END RSA PRIVATE KEY-----";
String str = new String(privKeyBytes);
if (str.contains(BEGIN) && str.contains(END)) {
str = str.substring(BEGIN.length(), str.lastIndexOf(END));
}
KeyFactory fac = KeyFactory.getInstance("RSA");
EncodedKeySpec privKeySpec =
new PKCS8EncodedKeySpec(Base64.decode(str.getBytes()));
return fac.generatePrivate(privKeySpec);
}
I get the exception
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid parse error, not a sequence
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:200) ~[na:1.6.0_23]
at java.security.KeyFactory.generatePrivate(KeyFactory.java:342) ~[na:1.6.0_23]
at the fac.generatePrivate(privKeySpec) call.
What does this error mean?
Thanks
Dmitri
Upvotes: 120
Views: 124795
Reputation: 5200
I faced a similar issue in Spring Boot REST API. I was calling DocuSign APIs from Spring Boot code. It was working fine in the local environment but after deploying the war file in Tomcat 9 server, it started throwing an error:
java.security.InvalidKeyException: IOException : algid parse error, not a sequence
Then I restarted the Tomcat service, and it started working as expected. Maybe Tomcat failed to load BouncyCastleProvider
into the classpath.
I hope this will be helpful to someone who visits this question in the future.
Upvotes: 0
Reputation: 1645
You must make your PCKS8 file from your private key!
openssl genrsa -out private.pem 1024
openssl rsa -in private.pem -pubout -outform PEM -out public_key.pem
openssl pkcs8 -topk8 -inform PEM -in private.pem -out private_key.pem -nocrypt
Upvotes: 90
Reputation: 4349
I was having this same issue, and the format of the key was NOT the actual problem.
All I had to do to get rid of that exception was to call
java.security.Security.addProvider(
new org.bouncycastle.jce.provider.BouncyCastleProvider()
);
and everything worked
Upvotes: 167
Reputation: 42018
It means your key is not in PKCS#8 format. The easiest thing to do is to use the openssl pkcs8 -topk8 <...other options...>
command to convert the key once. Alternatively you can use the PEMReader
class of the Bouncycastle lightweight API.
Upvotes: 114