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

Generate an RSA Key and Save to Encrypted PEM

See more RSA Examples

Demonstrates how to generate an RSA key and save to an encrypted PEM file.

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();

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

    // Generate a 2048-bit key.
    const priv_key = try chilkat.PrivateKey.init();
    defer priv_key.deinit();
    rsa.genKey(2048, priv_key) catch {
        std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
        return;
    };

    const password = "secret";
    // Saving to a relative path (from the current working directory of the process).
    var path: [:0]const u8 = "rsaKeys/myTestRsaPrivate.pem";
    // Encrypt the PEM using 256-bit AES encryption.
    priv_key.setPkcs8EncryptAlg("aes256");
    priv_key.savePkcs8EncryptedPemFile(password, path) catch {
        std.debug.print("{s}\n", .{try priv_key.getLastErrorText(alloc)});
        return;
    };

    // image

    // We can also save the public key.
    // There is no need to encrypt public keys.
    const pub_key = try chilkat.PublicKey.init();
    defer pub_key.deinit();
    priv_key.toPublicKey(pub_key) catch {};

    path = "rsaKeys/myTestRsaPublic.pem";
    // Choose PKCS1 or PKCS8
    // We'll choose PKCS8.
    const prefer_pkcs1 = false;
    pub_key.savePemFile(prefer_pkcs1, path) catch {
        std.debug.print("{s}\n", .{try pub_key.getLastErrorText(alloc)});
        return;
    };

    // image

    std.debug.print("Success.\n", .{});
}