1

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?

D.Tan
  • 115
  • 9
  • You probably want the [EncryptedPrivateKeyInfo](https://docs.oracle.com/javase/8/docs/api/javax/crypto/EncryptedPrivateKeyInfo.html) class. Also, there are no com.rsa.jsafe packages in the standard Oracle providers, so you appear to be using some special setup that may hinder getting help on SO. – President James K. Polk Aug 06 '17 at 19:34

1 Answers1

0

It ended up being a maven issue that was changing the path to the private.der file. Using the absolute path solved this issue.

D.Tan
  • 115
  • 9