Sample code for 30+ languages & platforms
Android™

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 Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    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 private key.
    CkPrivateKey privKey = new CkPrivateKey();
    success = privKey.LoadPemFile("qa_data/private_key.pem");
    if (success == false) {
        Log.i(TAG, privKey.lastErrorText());
        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.
    CkCert cert = new CkCert();
    success = cert.LoadFromFile("qa_data/cert.pem");
    if (success == false) {
        Log.i(TAG, cert.lastErrorText());
        return;
        }

    CkCertChain chain = new CkCertChain();
    success = cert.BuildCertChain(chain);
    if (success == false) {
        Log.i(TAG, cert.lastErrorText());
        return;
        }

    //  Add the private key and its certificate chain to the PFX.
    success = pfx.AddPrivateKey(privKey,chain);
    if (success == false) {
        Log.i(TAG, pfx.lastErrorText());
        return;
        }

    Log.i(TAG, "Private key and certificate chain added to the PFX.");

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}