Unicode C++
Unicode C++
RSA Encrypt Randomly Generated AES Key
See more RSA Examples
Demonstrates how to RSA encrypt a randomly generated AES key.Chilkat Unicode C++ Downloads
#include <CkPrngW.h>
#include <CkBinDataW.h>
#include <CkCertW.h>
#include <CkPublicKeyW.h>
#include <CkRsaW.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).
CkPrngW prng;
CkBinDataW bdAesKey;
success = prng.GenRandomBd(32,bdAesKey);
// Use a public key from a certificate for RSA encryption.
CkCertW cert;
success = cert.LoadFromFile(L"qa_data/pem/mf_public_rsa.pem");
if (success == false) {
wprintf(L"%s\n",cert.lastErrorText());
return;
}
CkPublicKeyW pubKey;
cert.GetPublicKey(pubKey);
CkRsaW rsa;
success = rsa.UsePublicKey(pubKey);
if (success == false) {
wprintf(L"%s\n",rsa.lastErrorText());
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) {
wprintf(L"%s\n",rsa.lastErrorText());
return;
}
// Return the result as a base64 string
const wchar_t *encryptedAesKey = bdAesKey.getEncoded(L"base64");
wprintf(L"encrypted AES key = %s\n",encryptedAesKey);
}