Creating a PrivateKey from PKCS12

I created a private key from a PKCS12 file with this command:

openssl pkcs12 -in test.p12 -nocerts -out privateKey.pem 

How can I create a PrivateKey object from this privateKey.pem file?

I tried using the PKCS12 file itself with this code:

  KeyStore pfx = KeyStore.getInstance("pkcs12"); pfx.load(new FileInputStream(P12), "123456".toCharArray()); final Enumeration<String> aliases = pfx.aliases(); //this is empty 

pfx.aliases() - was empty, I checked with keytool that it is really empty, no entries.

 keytool -v -list -storetype pkcs12 -keystore test.p12 Keystore type: PKCS12 Keystore provider: SunJSSE Your keystore contains 0 entries 

My question is: how can I create PrivateKey using this code:

  public static RSAPrivateKey getPrivateKey(File privateKeyFile) throws IOException { byte[] keyBytes = new byte[(int) privateKeyFile.length()]; FileInputStream fis = new FileInputStream(privateKeyFile); fis.read(keyBytes); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);// it works only with PKCS8 KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(spec); return privKey; } 

The problem with this code only works for PKCS8, I need something similar for PKCS12.

+4
source share
2 answers

The only way I know is a bit low level, but it works:

 public PrivateKey getPrivateKey(File file) throws IOException, GeneralSecurityException { try (FileInputStream fileStream = new FileInputStream(file); DataInputStream dataStream = new DataInputStream(fileStream)) { byte[] keyBytes = new byte[(int) file.length()]; dataStream.readFully(keyBytes); String temp = new String(keyBytes); String header = temp.replace("-----BEGIN PRIVATE KEY-----\n", ""); header = header.replace("-----END PRIVATE KEY-----", ""); byte[] decoded = new Base64().decode(header); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate(spec); } } 

This code assumes that the required key is an RSA key.

+2
source

You can try using KeyStore Explorer ( https://keystore-explorer.org/ ), which we use instead of Java Keytool (since I find it haunting).

0
source

Source: https://habr.com/ru/post/1500797/


All Articles