Is there any java API to convert certificate from 'DER' format to pkcs#12 format
-
09-10-2019 - |
Question
I need to convert certificate from DER format to pkcs#12 format. I know I can do this using openssl command. I am looking for java API / Class which can do this job. Any help will be appreciated.
Solution
You can try to load the PKCS#12 container as a keystore:
java.security.KeyStore ks = java.security.KeyStore.getInstance("PKCS12");
ks.load(new java.io.FileInputStream("yourStore.p12"), "yourPassword".toCharArray());
Once loaded, you can enumerate the elements inside the container:
for(Enumeration enum = ks.aliases(); enum.hasMoreElements(); ) {
String alias = (String) enum.nextElement();
System.out.println("@:" + alias);
if (ks.isKeyEntry(alias)) {
System.out.println("return PrivateKey");
PrivateKey pk = (PrivateKey) ks.getKey(alias, password);
// ...
}
}
OTHER TIPS
This can convert pkcs from PEM
openssl pkcs12 -export -in pem-certificate-and-key-file -out pkcs-12-certificate and-key-file
So lets convert your DER to PEM first
openssl dsa -inform PEM|DER -outform DER|PEM -in pem-file|der-file -out der-file|pem-file
As I understand it, PEM is simply the Base64 encoded string of the DER content with the appropriate header and footer lines. To convert to Base64 you can use javax.mail.internet.MimeUtility
for example.
I've gotten a lot of mileage out of Portecle.
If you must do it programmatically, much of what you need is in the KeyStore class in Java. As for user friendliness, well, it's pretty selective about its friends. Open a store, add to it, save it. If you need cert chains, that'll be a bit more complicated.
As for retrieving the cert from the DER encoding, see the X509Certificate javadoc. Especially the references to CertificateFactory.