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

RSA Encrypt Randomly Generated AES Key

See more RSA Examples

Demonstrates how to RSA encrypt a randomly generated AES key.

Chilkat PHP Downloads

PHP
<?php

use Chilkat2\BinData;
use Chilkat2\Cert;
use Chilkat2\Prng;
use Chilkat2\PublicKey;
use Chilkat2\Rsa;

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

// First generate a 256-bit AES key (32 bytes).
$prng = new Prng();
$bdAesKey = new BinData();
$prng->GenRandomBd(32, $bdAesKey);

// Use a public key from a certificate for RSA encryption.
$cert = new Cert();

try {
    $cert->LoadFromFile('qa_data/pem/mf_public_rsa.pem');

    $pubKey = new PublicKey();
    $cert->GetPublicKey($pubKey);

    $rsa = new Rsa();
    $rsa->UsePublicKey($pubKey);

    // RSA encrypt our 32-byte AES key.
    // The contents of bdAesKey are replaced with result of the RSA encryption.
    $rsa->EncryptBd($bdAesKey, false);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// Return the result as a base64 string
$encryptedAesKey = $bdAesKey->GetEncoded('base64');

echo 'encrypted AES key = ', $encryptedAesKey, "\n";