Perl Requires Chilkat v11.0.0+
Perl
RSA Encrypt Randomly Generated AES Key
See more RSA Examples
Demonstrates how to RSA encrypt a randomly generated AES key.Chilkat Perl Downloads
use strict;
use warnings;
use Chilkat2;
# 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).
my $prng = Chilkat2::Prng->new;
my $bdAesKey = Chilkat2::BinData->new;
my $success = $prng->GenRandomBd(32, $bdAesKey);
# Use a public key from a certificate for RSA encryption.
my $cert = Chilkat2::Cert->new;
$success = $cert->LoadFromFile('qa_data/pem/mf_public_rsa.pem');
if (!$success) {
print $cert->LastErrorText, "\n";
exit;
}
my $pubKey = Chilkat2::PublicKey->new;
$cert->GetPublicKey($pubKey);
my $rsa = Chilkat2::Rsa->new;
$success = $rsa->UsePublicKey($pubKey);
if (!$success) {
print $rsa->LastErrorText, "\n";
exit;
}
# RSA encrypt our 32-byte AES key.
# The contents of bdAesKey are replaced with result of the RSA encryption.
$success = $rsa->EncryptBd($bdAesKey, 0);
if (!$success) {
print $rsa->LastErrorText, "\n";
exit;
}
# Return the result as a base64 string
my $encryptedAesKey = $bdAesKey->GetEncoded('base64');
print 'encrypted AES key = ', $encryptedAesKey, "\n";