Sample code for 30+ languages & platforms
Java

Load Identities from PEM Text

See more PFX/P12 Examples

Demonstrates Pfx.LoadPem, which loads one or more certificate/private-key identities from PEM-formatted text and builds the contents of the Pfx object.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. The password decrypts any encrypted private keys in the PEM. This builds a PFX in memory from PEM material, which can then be serialized to PKCS#12.

Chilkat Java Downloads

Java
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    CkPfx pfx = new CkPfx();

    //  The file path is relative to the application's current working directory.  An absolute path
    //  may also be used.  Supply the path appropriate to your own environment.
    //  Load the PEM text (certificates and private keys) into a string.
    CkStringBuilder sbPem = new CkStringBuilder();
    boolean bLoaded = sbPem.LoadFile("qa_data/identity.pem");
    if (bLoaded != true) {
        System.out.println("Failed to load the PEM file.");
        return;
        }

    String pemText = sbPem.getAsString();
    if (sbPem.get_LastMethodSuccess() == false) {
        System.out.println(sbPem.lastErrorText());
        return;
        }

    //  The password decrypts any encrypted private keys in the PEM (use an empty string if none are
    //  encrypted).  A password should come from a secure source rather than being hard-coded.
    String password = "myPemPassword";
    success = pfx.LoadPem(pemText,password);
    if (success == false) {
        System.out.println(pfx.lastErrorText());
        return;
        }

    System.out.println("Loaded " + pfx.get_NumPrivateKeys() + " private key(s).");
  }
}