5

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);
zzchua
  • 53
  • 1
  • 4
  • If you mean you _must_ accept base64 (~ PEM, or DER) of PKCS1 RSAPrivateKey (aka OpenSSL's 'traditional' format) and can't fix it: if clear see https://stackoverflow.com/questions/3243018/how-to-load-rsa-private-key-from-file or my hack at https://stackoverflow.com/questions/23709898/java-convert-dkim-private-key-from-rsa-to-der-for-javamail for encrypted PEM (less likely?) see https://stackoverflow.com/questions/44681737/get-a-privatekey-from-a-rsa-pem-file or https://stackoverflow.com/questions/35276820/decrypting-an-openssl-pem-encoded-rsa-private-key-with-java – dave_thompson_085 Aug 12 '17 at 15:50
  • Your second paragraph doesn't make any sense. – President James K. Polk Aug 12 '17 at 16:39
  • Here is a solution: https://stackoverflow.com/a/55339208/975386 – Jean-Alexis Aufauvre Mar 25 '19 at 13:46

1 Answers1

-1

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-----
he shouyong
  • 159
  • 3