Sample code for 30+ languages & platforms
C++

RSA Encrypt Randomly Generated AES Key

See more RSA Examples

Demonstrates how to RSA encrypt a randomly generated AES key.

Chilkat C++ Downloads

C++
#include <CkPrng.h>
#include <CkBinData.h>
#include <CkCert.h>
#include <CkPublicKey.h>
#include <CkRsa.h>

void ChilkatSample(void)
    {
    bool success = false;

    // 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).
    CkPrng prng;
    CkBinData bdAesKey;
    success = prng.GenRandomBd(32,bdAesKey);

    // Use a public key from a certificate for RSA encryption.
    CkCert cert;

    success = cert.LoadFromFile("qa_data/pem/mf_public_rsa.pem");
    if (success == false) {
        std::cout << cert.lastErrorText() << "\r\n";
        return;
    }

    CkPublicKey pubKey;
    cert.GetPublicKey(pubKey);

    CkRsa rsa;
    success = rsa.UsePublicKey(pubKey);
    if (success == false) {
        std::cout << rsa.lastErrorText() << "\r\n";
        return;
    }

    // RSA encrypt our 32-byte AES key.
    // The contents of bdAesKey are replaced with result of the RSA encryption.
    success = rsa.EncryptBd(bdAesKey,false);
    if (success == false) {
        std::cout << rsa.lastErrorText() << "\r\n";
        return;
    }

    // Return the result as a base64 string
    const char *encryptedAesKey = bdAesKey.getEncoded("base64");

    std::cout << "encrypted AES key = " << encryptedAesKey << "\r\n";
    }