Sample code for 30+ languages & platforms
Zig

Get Public Key from CSR

See more CSR Examples

Demonstrates how to get the public key from a CSR.

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

    // This requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    const pem = try chilkat.Pem.init();
    defer pem.deinit();

    // No password is required.  Pass an empty password string..
    const no_password = "";
    pem.loadPemFile("qa_data/csr/csr2.pem", no_password) catch {
        std.debug.print("{s}\n", .{try pem.getLastErrorText(alloc)});
        return;
    };

    const str_base64 = try pem.getEncodedItem(alloc, "csr", "", "base64", 0);

    const asn = try chilkat.Asn.init();
    defer asn.deinit();
    asn.loadEncoded(str_base64, "base64") catch {
        std.debug.print("{s}\n", .{try asn.getLastErrorText(alloc)});
        return;
    };

    // Convert the ASN.1 to XML.
    const xml = try chilkat.Xml.init();
    defer xml.deinit();
    try xml.loadXml(try asn.asnToXml(alloc));
    std.debug.print("{s}\n", .{try xml.getXml(alloc)});
    std.debug.print("----\n", .{});

    const str_modulus_hex = try xml.getChildContent(alloc, "bits");
    std.debug.print("strModulusHex = {s}\n", .{str_modulus_hex});
    std.debug.print("----\n", .{});

    // We need the modulus as base64.
    const bd = try chilkat.BinData.init();
    defer bd.deinit();
    bd.appendEncoded(str_modulus_hex, "hex") catch {};
    const modulus64 = try bd.getEncoded(alloc, "base64");
    std.debug.print("modulus64 = {s}\n", .{modulus64});
    std.debug.print("----\n", .{});

    // Build the XML for the public key.
    const xml_pub_key = try chilkat.Xml.init();
    defer xml_pub_key.deinit();
    xml_pub_key.setTag("RSAPublicKey");
    xml_pub_key.updateChildContent("Modulus", modulus64);
    // The RSA exponent will always be decimal 65537 (base64 = AQAB)
    xml_pub_key.updateChildContent("Exponent", "AQAB");

    std.debug.print("RSA public key as XML:\n", .{});
    std.debug.print("{s}\n", .{try xml_pub_key.getXml(alloc)});
    std.debug.print("----\n", .{});

    // Load the XML into a Chilkat public key object.
    const pubkey = try chilkat.PublicKey.init();
    defer pubkey.deinit();
    pubkey.loadFromString(try xml_pub_key.getXml(alloc)) catch {
        std.debug.print("{s}\n", .{try pubkey.getLastErrorText(alloc)});
        return;
    };

    // Show the public key as PEM.
    const prefer_pkcs1 = true;
    std.debug.print("{s}\n", .{try pubkey.getPem(alloc, prefer_pkcs1)});
}