Sample code for 30+ languages & platforms
Java

Duplicate openssl pkcs12 –export –in certfile.cer –inkey certfile.key –out certfile.pfx

See more OpenSSL Examples

How to create a PKCS12 (.p12 or .pfx) from a certificate file and private key file: Demonstrates how to duplicate this OpenSSL command:
Duplicate openssl pkcs12 –export –in certfile.cer –inkey certfile.key –out certfile.pfx

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) {
        // This example assumes the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        PrivateKey pkey = new PrivateKey();

        // Load the private key from the file.
        try {
            pkey.loadAnyFormatFile("certFile.key", "");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        Cert cert = new Cert();
        // The LoadFromFile method auto-recognizes the format...
        try {
            cert.loadFromFile("certfile.cer");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // We'll need a cert chain object to create the PKCS12, so get it
        // from the cert.
        CertChain certChain = ERROR: Method not in Chilkat2 Java: Cert.GetCertChain
cert.ERROR();
        if (!cert.getLastMethodSuccess()) {
            System.out.println(cert.getLastErrorText());
            return;
        }

        // Create the PFX object, add the cert and private key, and write to a .pfx file.
        Pfx pfx = new Pfx();

        // The cert(s) are automatically added in the call to AddPrivateKey
        try {
            pfx.addPrivateKey(pkey, certChain);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Write the .pfx to a file.
        String password = "myPassword";
        try {
            pfx.toFile(password, "certfile.pfx");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println("Success.");
    }
}