Sample code for 30+ languages & platforms
Zig Requires Chilkat v11.0.0+

Generate a Random 256-bit AES Key and RSA Encrypt

See more RSA Examples

Generates a random 256-bit AES key and encrypts using an RSA public key. Only the owner of the RSA private key will be able to decrypt the AES key.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // The RSA public key is used for encryption, and the private key for decryption.

    // The public key's role is to make encryption accessible to anyone while ensuring that
    // only the private key holder can decrypt the messages.
    // The public key is designed to be widely distributed so anyone can use it to encrypt messages
    // intended for the owner of the private key.

    // Load our 2048-bit RSA public key.
    const pub_key = try chilkat.PublicKey.init();
    defer pub_key.deinit();
    // In all Chilkat methods expecting a path, you pass either absolute or relative paths.
    pub_key.loadFromFile("rsaKeys/Test2048Rsa.pem") catch {
        std.debug.print("{s}\n", .{try pub_key.getLastErrorText(alloc)});
        return;
    };

    const rsa = try chilkat.Rsa.init();
    defer rsa.deinit();

    // Tell RSA to use the public key.
    rsa.usePublicKey(pub_key) catch {};

    // Generate a random 256-bit AES key (32 bytes)
    const bd_aes_key = try chilkat.BinData.init();
    defer bd_aes_key.deinit();
    const prng = try chilkat.Prng.init();
    defer prng.deinit();
    prng.genRandomBd(32, bd_aes_key) catch {};

    // RSA encrypt.
    rsa.encryptBd(bd_aes_key, false) catch {};

    // Save the RSA encrypted AES key to a file.
    try bd_aes_key.writeFile("rsaEncrypted/myAes.key");
}