Sample code for 30+ languages & platforms
PHP Requires Chilkat v11.0.0+

Generate an RSA Key and Save to Encrypted PEM

See more RSA Examples

Demonstrates how to generate an RSA key and save to an encrypted PEM file.

Chilkat PHP Downloads

Chilkat2 PHP
<?php

use Chilkat2\PrivateKey;
use Chilkat2\PublicKey;
use Chilkat2\Rsa;

$rsa = new Rsa();

// Generate a 2048-bit key.
$privKey = new PrivateKey();
try {
    $rsa->GenKey(2048, $privKey);

    $password = 'secret';
    // Saving to a relative path (from the current working directory of the process).
    $path = 'rsaKeys/myTestRsaPrivate.pem';
    // Encrypt the PEM using 256-bit AES encryption.
    $privKey->Pkcs8EncryptAlg = 'aes256';
    $privKey->SavePkcs8EncryptedPemFile($password, $path);

    // image

    // We can also save the public key.
    // There is no need to encrypt public keys.
    $pubKey = new PublicKey();
    $privKey->ToPublicKey($pubKey);

    $path = 'rsaKeys/myTestRsaPublic.pem';
    // Choose PKCS1 or PKCS8
    // We'll choose PKCS8.
    $preferPkcs1 = false;
    $pubKey->SavePemFile($preferPkcs1, $path);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// image

echo "Success.\n";