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

Mister PKI

SSL Certificates * SSL Tools * Certificate Decoder

  • PKI Training
  • OpenSSL
  • Keytool
  • PKI Tools
    • Apereo CAS
    • SAML
    • OpenID Connect
  • Get expert help

Java read private key from file

April 14, 2022 by Mister PKI 1 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

Comments

  1. Karl says

    June 16, 2023 at 5:47 am

    Using libraries like https://github.com/KarlScheibelhofer/java-crypto-tools/ reading private keys and certificates in OpenSSL PEM format is even simpler.

    Reply

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

PKI for DevOps Engineers – Free Training Series

PKI for DevOps Training Hub

Lesson 1 – How TLS and PKI Work

Lesson 2 – Understanding X.509 Certificates

Lesson 3 – Certificate Chains Explained

Lesson 4 – Debug TLS with OpenSSL

Lesson 5 – Verify Certificate Chains

Lesson 6 – Creating CSRs with OpenSSL

Lesson 7 – Working with PKCS12 Certificates

Lesson 8 – Java Keystores and keytool

Lesson 9 – Certificate Expiration Monitoring

Lesson 10 – Automating Certificate Renewal

Lesson 11 – Common TLS Errors

Lesson 12 – PKI Architecture for DevOps

Recent Posts

  • Apache mod_auth_cas: Protect Web Applications with Apereo CAS and Docker
  • Apache mod_auth_mellon: Configure SAML SSO & Docker
  • Configure OpenID Connect (OIDC) in Apereo CAS 7.3 and 8
  • Certificate Ownership Is an Operating Model Problem, Not a Tooling Problem
  • OpenSSL dgst: Create Checksums and Verify Digital Signatures

Footer

  • Twitter
  • YouTube
Mister PKI

Practical security engineering for the systems that establish trust.

Learn OpenSSL Keytool Free training
Work together PKI consulting CAS consulting Sponsored contributions
Site About Support Mister PKI Cookie policy Search
© 2026 Mister PKI Secure systems. Clear guidance.