Java Requires Chilkat v11.0.0+
Chilkat2 Java
Load PKCS12 / PFX and Access Contents
See more PFX/P12 Examples
Loads a PKCS12 / PFX file and iterates over the contents which include private keys and certificates.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.Cert;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Pfx;
import com.chilkatsoft.chilkat2.PrivateKey;
public class ChilkatExample {
public static void main(String[] args) {
Pfx pfx = new Pfx();
// Load the PKCS12 from a file
try {
pfx.loadPfxFile("/someDir/my.p12", "pfxFilePassword");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
int numPrivateKeys = pfx.getNumPrivateKeys();
PrivateKey privKey = new PrivateKey();
System.out.println("Private Keys:");
int i = 0;
while (i < numPrivateKeys) {
pfx.privateKeyAt(i, privKey);
// Do something with the private key ...
i = i + 1;
}
Cert cert = new Cert();
int numCerts = pfx.getNumCerts();
System.out.println("Certs:");
i = 0;
while (i < numCerts) {
pfx.certAt(i, cert);
System.out.println(cert.getSubjectDN());
// If the certificate has a private key (one of the private keys within the PFX)
// then it can also be obtained via the certificate object:
if (cert.hasPrivateKey()) {
System.out.println("Has private key!");
cert.getPrivateKey(privKey);
// ...
}
i = i + 1;
}
}
}