Zig Requires Chilkat v11.0.0+
Zig
Generate an RSA Key and Get as Base64 DER
See more RSA Examples
Demonstrates how to generate a 2048-bit RSA key and return the public and private parts as unencrypted Base64 encoded DER.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 assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
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;
};
// Get the public part of the key.
const pub_key = try chilkat.PublicKey.init();
defer pub_key.deinit();
priv_key.toPublicKey(pub_key) catch {};
// There are two possible formats for representing the RSA public key
// in ASN.1 (DER). The possible formats are PKCS1 and PKCS8.
// We can get either by setting bChoosePkcs1 to true or false.
const b_choose_pkcs1 = true;
const pub_key_base64_der = try pub_key.getEncoded(alloc, b_choose_pkcs1, "base64");
std.debug.print("Public Key Base64 DER:\n", .{});
std.debug.print("{s}\n", .{pub_key_base64_der});
// Get the private key as Base64 DER:
// We can get PKCS1 or PKCS8, but with different methods:
const priv_key_pkcs1 = try priv_key.getPkcs1ENC(alloc, "base64");
std.debug.print("Private Key PKCS1 Base64 DER:\n", .{});
std.debug.print("{s}\n", .{priv_key_pkcs1});
const priv_key_pkcs8 = try priv_key.getPkcs8ENC(alloc, "base64");
std.debug.print("Private Key PKCS8 Base64 DER:\n", .{});
std.debug.print("{s}\n", .{priv_key_pkcs8});
}