Sample code for 30+ languages & platforms
Android™

Load an Encrypted Private Key from PEM Text

See more Private Key Examples

Demonstrates the Chilkat PrivateKey.LoadEncryptedPem method, which loads a private key from PEM text, using a password when the PEM is encrypted. The first argument is the PEM string and the second is the password. Unencrypted PEM is also accepted.

Background: An encrypted PEM protects the key material at rest — a stolen file is useless without the passphrase — which is why encrypted keys are preferred for anything shipped or stored. This loader supplies that passphrase to decrypt a BEGIN ENCRYPTED PRIVATE KEY block (and gracefully handles unencrypted PEM too), so it is a safe default when a PEM might be either. The password should come from a secure source, never a hard-coded literal.

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;

    //  Demonstrates the PrivateKey.LoadEncryptedPem method, which loads a private key from PEM text.
    //  The 1st argument is the PEM string and the 2nd is the password (used when the PEM is
    //  encrypted).  Unencrypted PEM is also accepted.

    CkPrivateKey privKey = new CkPrivateKey();

    //  The PEM text of an encrypted private key.
    String pemText = "-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIFHzBJ...\n-----END ENCRYPTED PRIVATE KEY-----";

    //  The key password is not hard-coded in a real application; obtain it from an interactive
    //  prompt, environment variable, or a secrets vault.
    String password = "myKeyPassword";

    success = privKey.LoadEncryptedPem(pemText,password);
    if (success == false) {
        Log.i(TAG, privKey.lastErrorText());
        return;
        }

    Log.i(TAG, "Loaded a " + privKey.keyType() + " private key.");

  }

  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."
  }
}