Convert an RSA PKCS1 private key string to a Java PrivateKey object

Viewed 4662

I have a RSA private key stored as a String that I need to convert into a PrivateKey object for use with an API. I can find examples of people converting from a private-key file to a string but not the other way around.

I managed to convert it to a PrivateKey object but it was in PKCS8, when I need it to be PKCS1, and I know Java doesn't have PKCS1EncodedKeySpec

byte[] key64 = Base64.decodeBase64(privateKeyString.getBytes());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
KeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
1 Answers

you can convert pkcs#1 to pkcs#8

openssl pkcs8 -topk8 -in server.key -nocrypt -out server_pkcs8.key
cat server_pkcs8.key 
-----BEGIN PRIVATE KEY-----
base64_encode xxx
-----END PRIVATE KEY-----
Related