I originally have a password-protected PEM file with a private key that is read into a Java application using BouncyCastle. The PEM file begins with
-----BEGIN RSA PRIVATE KEY-----
which leads me to believe it is in the PKCS#1 format. Instead of using the PEM file, I want to generate a binary file and read the private key into the Java program. As per here, I used the following openssl code to generate a DER file:
openssl pkcs8 -topk8 -nocrypt -in private.pem -outform der -out private.der
Then used this Java code to try to read in the DER file:
Path path = Paths.get(privateKeyLocation);
byte[] byteArray = Files.readAllBytes(path);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(byteArray);
PrivateKey privKey;
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
privKey = keyFactory.generatePrivate(keySpec);
} catch (InvalidKeySpecException e) {
logger.error("error with jwt", e);
return null;
} catch (NoSuchAlgorithmException e) {
logger.error("error with jwt", e);
return null;
}
But I'm running into this error:
java.lang.NoClassDefFoundError: com/rsa/asn1/ASN_Exception
at com.rsa.jsafe.provider.JS_KeyFactory.b(Unknown Source)
at com.rsa.jsafe.provider.JS_KeyFactory.engineGeneratePrivate(Unknown Source)
at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
...
I'm not sure what is causing this error and wonder if there's a better way to use BouncyCastle to read in a DER file?
It ended up being a maven issue that was changing the path to the private.der
file. Using the absolute path solved this issue.