React Native Requires Chilkat v11.0.0+
React Native
RSA Encrypt Randomly Generated AES Key
See more RSA Examples
Demonstrates how to RSA encrypt a randomly generated AES key.Chilkat React Native Downloads
import { BinData, Cert, Prng, PublicKey, Rsa } from '@chilkat/react-native'
function chilkatExample() {
// 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).
const prng = new Prng();
const bdAesKey = new BinData();
prng.genRandomBd(32, bdAesKey);
// Use a public key from a certificate for RSA encryption.
const cert = new Cert();
try {
cert.loadFromFile('qa_data/pem/mf_public_rsa.pem');
} catch {
console.log(cert.lastErrorText);
return;
}
const pubKey = new PublicKey();
cert.getPublicKey(pubKey);
const rsa = new Rsa();
try {
rsa.usePublicKey(pubKey);
} catch {
console.log(rsa.lastErrorText);
return;
}
// RSA encrypt our 32-byte AES key.
// The contents of bdAesKey are replaced with result of the RSA encryption.
try {
rsa.encryptBd(bdAesKey, false);
} catch {
console.log(rsa.lastErrorText);
return;
}
// Return the result as a base64 string
const encryptedAesKey = bdAesKey.getEncoded('base64');
console.log(`encrypted AES key = ${encryptedAesKey}`);
}