• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Mister PKI

SSL Certificates * SSL Tools * Certificate Decoder

  • Buy SSL Certificates
  • Blog
  • OpenSSL
  • Keytool
  • SSL Tools
  • Donate

Java read private key from file

April 14, 2022 by Mister PKI Leave a Comment

This article will demonstrate how to in Java read private key from file. Let us assume that you have a pem encoded RSA private key in a file that you want to load into the Java PrivateKey object.

The first two steps are for generating a private key and storing it in a file. Skip to step 3 if you already have a pem encoded private key.

  1. generate an RSA private key using the Java keytool.
  2. Extract the private key from the keystore using OpenSSL. See this post for more details.
openssl pkcs12 -in keystore.p12 -nodes -nocerts -out key.pem
  1. Create a Java class to read the pem encoded private key and store in a PrivateKey object.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
public class PrivateKeyReader {
    public static void main(String args[]) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
        byte[] key = Files.readAllBytes(Paths.get("key.pem"));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key);
        PrivateKey finalKey = keyFactory.generatePrivate(keySpec);
        System.out.println(finalKey.getAlgorithm());
    }
}
  1. Load the key file into an array of bytes.
  2. Create a Java KeyFactory object of RSA.
  3. Create a PKCS8EncodedKeySpec object containing the loaded key.
  4. Create the Java PrivateKey object.
  5. Print out the key algorithm to verify it was successfully created.

Note that if you receiving the following error, you will need to convert your private key to be PKCS8 formatted. To convert the pem encoded private key to pkcs8 format run the following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in key.pem -out key2.pem -nocrypt
Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
	at java.base/sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:251)
	at java.base/java.security.KeyFactory.generatePrivate(KeyFactory.java:390)
	at PrivateKeyReader.main(PrivateKeyReader.java:17)
Caused by: java.security.InvalidKeyException: invalid key format
	at java.base/sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:330)
	at java.base/sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:355)
	at java.base/sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:130)
	at java.base/sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:80)
	at java.base/sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:356)
	at java.base/sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:247)
	... 2 more

Debug Java Private Key

Using your favorite IDE (Integrated Development Environment) you may also debug and inspect the generated Java private key. Our recommended IDE is IntelliJ.

Java Private Key Intellij Debug

Conclusion – Java read private key from file

In conclusion, this article has demonstrated how to read a private key from a file and convert to a Java PrivateKey object. Let us know in the comments if you have any questions or would like to see additional examples.

java

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Popular Posts

PKCS12

openssl s_client

Keytool

Keytool list

ECDSA vs RSA

OpenSSL

PKCS7

Certificate Decoder

Training Courses

Top online courses in IT & Software

Cyber Security Training

Udemy - The Complete Internet Security Privacy Course icon

Buy SSL Certificates

The SSL Store

Comodo Store

Sectigo Store

RapidSSL

Recent Posts

  • pfx password
  • pkcs12
  • Sendmail vs Postfix – Mail Transfer Agent Comparison
  • Python mock datetime now
  • Python get SSL Certificate

Footer

  • Twitter
  • YouTube

Pages

  • About Mister PKI
  • Blog
  • Compare and Buy Affordable PKI Certificates
  • Contact Us
  • Full Disclosure
  • Privacy Policy
  • SSL Tools – Certificate Decoder and Certificate Checker

Copyright © 2022