Sample code for 30+ languages & platforms
Java

Add a Private Key and Certificate Chain to a PFX

See more PFX/P12 Examples

Demonstrates Pfx.AddPrivateKey, which adds a private key together with its certificate chain to 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 chain must contain at least one certificate; the certificate at index 0 is treated as the leaf. The chain is built here with Cert.BuildCertChain.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.Cert;
import com.chilkatsoft.chilkat2.CertChain;
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();

        // 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 private key.
        PrivateKey privKey = new PrivateKey();
        try {
            privKey.loadPemFile("qa_data/private_key.pem");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Load the certificate and build its chain of authority.  The chain must contain at least one
        // certificate; the certificate at index 0 is treated as the leaf.
        Cert cert = new Cert();
        try {
            cert.loadFromFile("qa_data/cert.pem");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        CertChain chain = new CertChain();
        try {
            cert.buildCertChain(chain);

            // Add the private key and its certificate chain to the PFX.
            pfx.addPrivateKey(privKey, chain);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println("Private key and certificate chain added to the PFX.");
    }
}