Zig
Zig
Generate RSA SSH Key
See more SSH Key Examples
Generates an RSA SSH key and saves to various public and private key file formats (OpenSSH and PuTTY).Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
const key = try chilkat.SshKey.init();
defer key.deinit();
// numBits may range from 384 to 4096. Typical values are
// 1024 or 2048. (must be a multiple of 64)
// A good choice for the exponent is 65537. Chilkat recommends
// always using this value.
const num_bits = 2048;
const exponent = 65537;
key.generateRsaKey(num_bits, exponent) catch {
std.debug.print("Bad params passed to RSA key generation method.\n", .{});
return;
};
// Note: Generating a public/private key pair is CPU intensive
// and may take a short amount of time (more than few seconds,
// but less than a minute).
var exported_key: [:0]const u8 = "";
var export_encrypted: bool = false;
// Export the RSA private key to OpenSSH, PuTTY, and XML and save.
export_encrypted = false;
exported_key = try key.toOpenSshPrivateKey(alloc, export_encrypted);
// Chilkat provides a SaveText method for convenience...
try key.saveText(exported_key, "privkey_openssh_unencrypted.pem");
// Export with encryption to OpenSSH private key format:
key.setPassword("secret");
export_encrypted = true;
exported_key = try key.toOpenSshPrivateKey(alloc, export_encrypted);
try key.saveText(exported_key, "privkey_openssh_encrypted.pem");
// Export the RSA private key to unencrypted PuTTY format:
export_encrypted = false;
exported_key = try key.toPuttyPrivateKey(alloc, export_encrypted);
try key.saveText(exported_key, "privkey_putty_unencrypted.ppk");
// Export the RSA private key to encrypted PuTTY format:
key.setPassword("secret");
export_encrypted = true;
exported_key = try key.toPuttyPrivateKey(alloc, export_encrypted);
try key.saveText(exported_key, "privkey_putty_encrypted.ppk");
// Export private key to XML:
exported_key = try key.toXml(alloc);
try key.saveText(exported_key, "privkey.xml");
// ----------------------------------------------------
// Now for the public key....
// ----------------------------------------------------
// The Secure Shell (SSH) Public Key File Format
// is documented in RFC 4716.
exported_key = try key.toRfc4716PublicKey(alloc);
try key.saveText(exported_key, "pubkey_rfc4716.pub");
// OpenSSH has a separate public-key file format, which
// is also supported by Chilkat SshKey:
exported_key = try key.toOpenSshPublicKey(alloc);
try key.saveText(exported_key, "pubkey_openSsh.pub");
std.debug.print("Finished.\n", .{});
}