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

Generate RSA Public/Private Key Pair and Export to PEM

See more RSA Examples

_LANGUAGE_ example code showing how to generate an RSA public/private key pair and export to PEM files.

Chilkat PHP Downloads

PHP
<?php

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

// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

$rsa = new Rsa();

// Generate a 2048-bit key.  Chilkat RSA supports
// key sizes ranging from 512 bits to 8192 bits.
$privKey = new PrivateKey();
try {
    $rsa->GenKey(2048, $privKey);

    $pubKey = new PublicKey();
    $privKey->ToPublicKey($pubKey);

    // Save the private key in PEM format:
    $privKey->SavePemFile('privateKey.pem');

    // Save the public key in PEM format:
    $pubKey->SavePemFile(false, 'publicKey.pem');
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

echo "Success.\n";