PKCS#12 standard is part of the Public Key Cryptography Standards and defines a file format where private keys and certificates can be stored.A PKCS#12 file has often a .p12 extention and in this tutorial we will see how to extract the private key and the certificate from a .p12 file.

As a first step we need to create a PKCS instance of a Keystore object where the contents of the PKCS file will be loaded.

Finally,since each entry in the keystore is distinguished by a string alias we will use this alias to retrieve the private key and the certificate.

import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class Ggre {

	public static void main(String[] args) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException{
		
		String alias="";
//initilize keyStore
		KeyStore ks = KeyStore.getInstance("PKCS12");
		FileInputStream ksin = new FileInputStream("C:\\the_p12_file.p12");
		//load .p12 file contents
		ks.load(ksin,"17*SoWeIT".toCharArray());
		//for every alias get the private key and the certificate
		Enumeration objEnumeration = ks.aliases(); 
    	while (objEnumeration.hasMoreElements () == true) {
    		alias = objEnumeration.nextElement ();
    		System.out.println(alias);
PrivateKey privateKey = null;
		X509Certificate cert = null;
		privateKey = (PrivateKey) ks.getKey(alias,"17*SoWeIT".toCharArray()) ;
    	cert = (X509Certificate)ks.getCertificate(alias);
    	System.out.println("PRIVATE KEY:"+ privateKey.toString());
System.out.println("CERTIFICATE:"+cert.toString());
    	}
    	

	}
}