How to read p12 file from system in Java?

10,194

I built a quick and dirty little class to show the opening of a relative .pfx (P12) that I created with keytools. Naturally, you can also look through different potential directories looking for the file, if there are a couple likely places for it to be.

The file structure looks like this:

./bin
./bin/Test.java
./bin/Test.class
./conf
./conf/myFile.pfx

Here's the test code:

import java.io.*;
import java.security.*;

class Test {
  public static void main(String[] args) {
    String pass = "password";
    try {
      File file = new File("../conf/myFile.pfx");
      InputStream stream = new FileInputStream(file);
      KeyStore store = KeyStore.getInstance("PKCS12");
      store.load(stream, pass.toCharArray());
      PrivateKey key = (PrivateKey)store.getKey("example", pass.toCharArray());
      System.out.println("Success");
    } catch (KeyStoreException kse) {
      System.err.println("Error getting the key");
    } catch (Exception e) {
      System.err.println("Error opening the key file");
      e.printStackTrace();
    }
  }
}
Share:
10,194
Adam Bronfin
Author by

Adam Bronfin

Updated on June 04, 2022

Comments

  • Adam Bronfin
    Adam Bronfin almost 2 years

    In my application I make use of a p12 certificate file to encrypt traffic when talking to an API I am using.

    For my production environment, I need to read these files off the system rather than from the application.

    On Linux, how might I read these files off my system into my application into an InputStream just like I would from a resources directory in my application?

    I am using Java.