0
votes

InvalidKeyException is throw while trying to read SSLeay Format private key.

Please find below the details:- I have a SSLeay Format private key.The pem format begins with the below file

-----BEGIN RSA PRIVATE KEY-----

I am writing the code to get the private key saved in a byte format and convert the same to PrivateKey. Variable privateKeyBytes contains the private key in byte format/

String pkStrFormat = new String(privateKeyBytes, "UTF-8");
pkStrFormat = pkStrFormat.replaceAll("(-----BEGIN RSA PRIVATE KEY-----\\r?\\n|-----END RSA PRIVATE KEY-----+\\r?\\n?)","");
byte[] keyBytesOfPrivateKey = org.bouncycastle.util.encoders.Base64
                    .decode(pkStrFormat.getBytes());
KeyFactory ecKeyFac = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytesOfPrivateKey);            
PrivateKey priKey = ecKeyFac.generatePrivate(keySpec);

I am getting the below exception:-

Caused by: java.security.InvalidKeyException: IOException : version mismatch: (supported:     00, parsed:     01
    at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:350)
    at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:356)

The code works fine when PKCS8 Format keys are used.

1

1 Answers

2
votes

PEM files starting with BEGIN RSA PRIVATE KEY are PKCS#1, not PKCS#8. PKCS#1 is essentially PKCS#8 for fixed algorithm RSA and therefore with algorithm identifier removed. Either convert your key like in https://superuser.com/questions/606215/openssl-pkcs8-default-format-gives-rsa-private-key:

openssl pkcs8 -topk8 -inform pem -in file.key -outform pem -nocrypt -out file.pem

or use PEMParser similar to Bouncy Castle : PEMReader => PEMParser (without the password stuff)