Sample code for 30+ languages & platforms
Java

Load an Encrypted PKCS #8 Private Key File

See more Private Key Examples

Demonstrates the Chilkat PrivateKey.LoadPkcs8EncryptedFile method, which loads a private key from a file, using a password when the key is encrypted. The first argument is the file path and the second is the password. It handles encrypted PKCS #8 DER or PEM, and unencrypted forms.

Note: The file path is relative to the application's current working directory. Absolute paths may also be used. Supply the path to your own key file.

Background: Encrypted PKCS #8 is the standard way to store a password-protected key in either binary DER or Base64 PEM. This loader decrypts both, and because it also accepts unencrypted input it is a robust choice when a PKCS #8 file may or may not be encrypted. As always, source the password securely.

Chilkat Java Downloads

Java
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    //  Demonstrates the PrivateKey.LoadPkcs8EncryptedFile method, which loads a private key from a
    //  file, using a password when the key is encrypted.  The 1st argument is the file path and the
    //  2nd is the password.  It handles encrypted PKCS #8 DER or PEM, as well as unencrypted forms.

    CkPrivateKey privKey = new CkPrivateKey();

    //  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.LoadPkcs8EncryptedFile("qa_data/private_pkcs8_enc.der",password);
    if (success == false) {
        System.out.println(privKey.lastErrorText());
        return;
        }

    System.out.println("Loaded a " + privKey.keyType() + " private key.");
  }
}