Sample code for 30+ languages & platforms
Java

Export an Encrypted PKCS #8 Private Key as PEM

See more Private Key Examples

Demonstrates the Chilkat PrivateKey.GetPkcs8EncryptedPem method, which exports the key as password-protected PKCS #8 PEM (-----BEGIN ENCRYPTED PRIVATE KEY-----). The only argument is the password; the cipher is selected by the Pkcs8EncryptAlg property.

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: This is the safe way to export a key for storage or transfer — the private material is encrypted under a passphrase, so a leaked file is not immediately usable. It is the format to reach for whenever a key leaves your process. Control the encryption cipher with Pkcs8EncryptAlg, and source the password securely rather than hard-coding it.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.PrivateKey;

public class ChilkatExample {

    public static void main(String[] args) {
        // Load a private key to export.
        PrivateKey privKey = new PrivateKey();
        try {
            privKey.loadPemFile("qa_data/private.pem");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            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";

        // Export as password-protected PKCS #8 PEM ("-----BEGIN ENCRYPTED PRIVATE KEY-----").  The
        // encryption cipher is selected by the Pkcs8EncryptAlg property.
        String pem;
        try {
            pem = privKey.getPkcs8EncryptedPem(password);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println(pem);
    }
}