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.