Dart Requires Chilkat v11.0.0+
Dart
RSA Encrypt Randomly Generated AES Key
See more RSA Examples
Demonstrates how to RSA encrypt a randomly generated AES key.Chilkat Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
// 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).
final prng = CkPrng();
final bdAesKey = CkBinData();
prng.genRandomBd(32, bdAesKey);
// Use a public key from a certificate for RSA encryption.
final cert = CkCert();
try {
cert.loadFromFile('qa_data/pem/mf_public_rsa.pem');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
final pubKey = CkPublicKey();
cert.getPublicKey(pubKey);
final rsa = CkRsa();
try {
rsa.usePublicKey(pubKey);
} on ChilkatException catch (e) {
print(e.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);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
// Return the result as a base64 string
final encryptedAesKey = bdAesKey.getEncoded('base64');
print('encrypted AES key = $encryptedAesKey');
}