Sample code for 30+ languages & platforms
Zig

Convert a PuTTY Private Key (.ppk) to OpenSSH (.pem)

See more SSH Examples

Demonstrates converting a PuTTY format private key to OpenSSH format. The .ppk is imported with FromPuttyPrivateKey and re-exported with ToOpenSshPrivateKey, both unencrypted and encrypted.

Note: The file paths are relative to the application's current working directory. Supply the paths to your own files.

Background: PuTTY and OpenSSH store the same underlying key material in different container formats, so converting between them is a re-encoding rather than a new key — the corresponding public key, and therefore the server-side authorized_keys entry, is unchanged. This matters when moving between Windows tooling built around PuTTY and Unix tooling that expects PEM. Note that the Password property serves double duty: it decrypts the key on import and encrypts it on export, so set it appropriately for each step.

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

    // Demonstrates converting a PuTTY format private key (.ppk) to OpenSSH (.pem) format.

    const key = try chilkat.SshKey.init();
    defer key.deinit();

    // Set the password before importing an encrypted PuTTY key.  If the key is not encrypted it
    // makes no difference whether Password is set.  This should come from a secure source rather
    // than being hard-coded.
    key.setPassword("myKeyPassword");

    // LoadText is a convenience method that reads any text file into a string.  It does not itself
    // load the key.
    const key_str = key.loadText(alloc, "qa_data/putty_private_key.ppk") catch {
        std.debug.print("{s}\n", .{try key.getLastErrorText(alloc)});
        return;
    };

    key.fromPuttyPrivateKey(key_str) catch {
        std.debug.print("{s}\n", .{try key.getLastErrorText(alloc)});
        return;
    };

    // Export to an unencrypted OpenSSH key.
    var b_encrypt: bool = false;
    const unencrypted_key_str = key.toOpenSshPrivateKey(alloc, b_encrypt) catch {
        std.debug.print("{s}\n", .{try key.getLastErrorText(alloc)});
        return;
    };

    key.saveText(unencrypted_key_str, "qa_output/unencrypted_openssh.pem") catch {
        std.debug.print("{s}\n", .{try key.getLastErrorText(alloc)});
        return;
    };

    // Export to an encrypted OpenSSH key.  The Password property supplies the passphrase used to
    // encrypt the output.
    b_encrypt = true;
    key.setPassword("myExportPassword");
    const encrypted_key_str = key.toOpenSshPrivateKey(alloc, b_encrypt) catch {
        std.debug.print("{s}\n", .{try key.getLastErrorText(alloc)});
        return;
    };

    key.saveText(encrypted_key_str, "qa_output/encrypted_openssh.pem") catch {
        std.debug.print("{s}\n", .{try key.getLastErrorText(alloc)});
        return;
    };

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