Sample code for 30+ languages & platforms
Android™

Save a Private Key as an Encrypted PKCS #8 PEM File

See more Private Key Examples

Demonstrates the Chilkat PrivateKey.SavePkcs8EncryptedPemFile method, which saves the key as password-protected PKCS #8 PEM (the ENCRYPTED PRIVATE KEY label). The first argument is the password and the second is the destination path.

Note: The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background: The text (PEM) form of an encrypted saved key — portable across systems and safe to store because the private material is protected by a passphrase. It is the encrypted counterpart to SavePkcs8PemFile and a good default for keys kept in configuration or version-controlled deployment repositories. Source the password securely.

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;

    //  Load a private key to export.
    CkPrivateKey privKey = new CkPrivateKey();
    success = privKey.LoadPemFile("qa_data/private.pem");
    if (success == false) {
        Log.i(TAG, privKey.lastErrorText());
        return;
        }

    //  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";

    //  Save as password-protected PKCS #8 PEM (the "ENCRYPTED PRIVATE KEY" label).  The 1st argument
    //  is the password and the 2nd is the destination path.
    success = privKey.SavePkcs8EncryptedPemFile(password,"qa_output/private_pkcs8_enc.pem");
    if (success == false) {
        Log.i(TAG, privKey.lastErrorText());
        return;
        }

    Log.i(TAG, "Saved (encrypted).");

  }

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