0

I have a String containing the key in the format:

"-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----"

I am looking to get a PrivateKey from this but I am currently getting a java.security.InvalidKeyException: Missing key encoding. My code is the following:

       java.security.Security.addProvider(new BouncyCastleProvider());

       String privateKey = this.privateKey
                .replace("-----BEGIN RSA PRIVATE KEY-----", "")
                .replaceAll("\\n", "")
                .replace("-----END RSA PRIVATE KEY-----", "");

        byte[] derPrivateKey = Base64.decode(privateKey);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(derPrivateKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(spec);

From what I just read I see this key is in the encoding PKCS1 rather than PKCS8. Im not sure what to do from here to if anyone is able to point me in the right direction it would be much appreciated, thanks.

  • Bouncy Castle is been able to read these kind of keys – Michael Fehr Jan 07 '22 at 16:50
  • @MichaelFehr+ but using its own API `PEMParser` + `JcaPEMKeyConverter` + if encrypted `Jce{PEM|PKCSPBEInput}DecryptorProviderBuilder` (!) not standard-JCA `KeyFactory`. See e.g. https://stackoverflow.com/questions/22920131/ https://stackoverflow.com/questions/14919048/ https://stackoverflow.com/questions/44681737/ and list at https://stackoverflow.com/questions/58753399/ – dave_thompson_085 Jan 07 '22 at 17:03

0 Answers0