简体   繁体   中英

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

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);

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-----

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM