Sample code for 30+ languages & platforms
Zig

Get the Public Key from a Private Key

See more Private Key Examples

Demonstrates the Chilkat PrivateKey.ToPublicKey method, which extracts the public portion of the loaded private key into an independent PublicKey object. The only argument is the PublicKey that receives the copy.

Note: The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background: A key pair's public half is derived from the private half, and this is how you obtain it — the public key you distribute for others to verify signatures or encrypt to you, while the private key stays secret. The resulting PublicKey is an independent copy, so exporting or sharing it never risks exposing the private material. From there, export it as PEM, JWK, or XML as needed.

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

    // Load a private key to export.
    const priv_key = try chilkat.PrivateKey.init();
    defer priv_key.deinit();
    priv_key.loadPemFile("qa_data/private.pem") catch {
        std.debug.print("{s}\n", .{try priv_key.getLastErrorText(alloc)});
        return;
    };

    // Extract the public portion of the private key into an independent PublicKey object.  The
    // PublicKey is a separate copy, unaffected by later changes to the PrivateKey.
    const pub_key = try chilkat.PublicKey.init();
    defer pub_key.deinit();
    priv_key.toPublicKey(pub_key) catch {
        std.debug.print("{s}\n", .{try priv_key.getLastErrorText(alloc)});
        return;
    };

    // The PublicKey can now be exported or shared -- for example as PEM.  The argument prefers the
    // traditional PKCS #1 PEM when a traditional representation exists.
    const prefer_pkcs1 = true;
    const pub_pem = pub_key.getPem(alloc, prefer_pkcs1) catch {
        std.debug.print("{s}\n", .{try pub_key.getLastErrorText(alloc)});
        return;
    };

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