Zig Requires Chilkat v11.0.0+
Zig
RSA Encrypt Randomly Generated AES Key
See more RSA Examples
Demonstrates how to RSA encrypt a randomly generated AES key.Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// 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 = try chilkat.Prng.init();
defer prng.deinit();
const bd_aes_key = try chilkat.BinData.init();
defer bd_aes_key.deinit();
try prng.genRandomBd(32, bd_aes_key);
// Use a public key from a certificate for RSA encryption.
const cert = try chilkat.Cert.init();
defer cert.deinit();
cert.loadFromFile("qa_data/pem/mf_public_rsa.pem") catch {
std.debug.print("{s}\n", .{try cert.getLastErrorText(alloc)});
return;
};
const pub_key = try chilkat.PublicKey.init();
defer pub_key.deinit();
cert.getPublicKey(pub_key) catch {};
const rsa = try chilkat.Rsa.init();
defer rsa.deinit();
rsa.usePublicKey(pub_key) catch {
std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
return;
};
// RSA encrypt our 32-byte AES key.
// The contents of bdAesKey are replaced with result of the RSA encryption.
rsa.encryptBd(bd_aes_key, false) catch {
std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
return;
};
// Return the result as a base64 string
const encrypted_aes_key = try bd_aes_key.getEncoded(alloc, "base64");
std.debug.print("encrypted AES key = {s}\n", .{encrypted_aes_key});
}