Sample code for 30+ languages & platforms
Zig

Generate DSA SSH Key

See more SSH Key Examples

Generates a DSA SSH key and saves to various public and private key file formats (OpenSSH and PuTTY).

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 key = try chilkat.SshKey.init();
    defer key.deinit();

    // numBits should be a minimum of 1024 and
    // a multiple of 64.  Typical values are
    // 1024 or 2048.
    const num_bits = 2048;
    key.generateDsaKey(num_bits) catch {
        std.debug.print("Invalid numBits passed to DSA 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 DSA 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 DSA 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 DSA 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", .{});
}