Java convert pfx to a format that can be imported into the default keystore

I programmatically upload a certificate to the default keystore with the following code

KeyStore kStore = KeyStore.getInstance(KeyStore.getDefaultType()); java.io.FileInputStream fis = new FileInputStream(keystorePath); kStore.load(fis, new String(keystorePass).toCharArray()); fis.close(); 

I have a third-party certificate in pfx format. If I try to download it, it will end with an invalid format.

If I upgrade to use the following, it works. But I do not want to change the code.

 KeyStore keystore = KeyStore.getInstance("PKCS12"); 

How to convert the pfx file to a format that will be adopted next

 KeyStore kStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
+4
source share
2 answers

A certificate is never simple. You need to open openssl (the version of Cygwin runs on Windows) to convert the pfx / p12 file to a pem file, then you can create a certificate from pem. Finally, you can use the Java keytool program to convert the certificate to the JKS format (default for KeyStore).

Convert pfx to pem:

 openssl pkcs12 -in whatever.pfx -out whatever.pem -clcerts -nokeys 

Create an X509 certificate from the pem file:

 openssl x509 -in whatever.pem -inform PEM -out whatever.crt -outform DER 

Use Java keytool to create a JKS file from a certificate:

 keytool -import -trustcacerts -keystore whatever.jks -storepass somepassword -noprompt -file whatever.crt -alias localhost 

Note that -alias can be any unique name that you want to use for this certificate. The agreement is to use the URL of your website.

Now you can load the JKS file with the KeyStore instance into your code. Maybe it's easier to just change your Java code to use a PKCS12 instance?

+2
source

If I upgrade to use the following, it works. But I do not want to change the code.

KeyStore keystore = KeyStore.getInstance ("PKCS12"); How can I convert the pfx file to a format that will be accepted next

KeyStore kStore = KeyStore.getInstance (KeyStore.getDefaultType ());

Why not?
The default storage format for Java is JKS.

But there are other formats, and #PKCS12 is the most commonly used.

If you want the application to be more "reliable", I would recommend not converting the file you have into JKS format.

Instead, you can support more than JKS and, for example, try the default storage type and if it doesn't work, try #PKCS12

I would go further and suggest that KeyStore.getInstance(KeyStore.getDefaultType()); replaced by something like:

KeyStore.getInstance(UserPreferences.getDefaultType());

where the user chose which should be the default repository file (maybe # PKCS12)

0
source

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


All Articles