Sample code for 30+ languages & platforms
Zig

Convert ASN.1 to/from Binary DER, XML, and Base64

Demonstrates how to convert ASN.1 from and to any of the following formats: binary DER, Base64, and XML.

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

    // Begin with loading ASN.1 from a binary DER/BER format file.
    asn.loadBinaryFile("/Users/chilkat/testData/p7b/test.p7b") catch {
        std.debug.print("{s}\n", .{try asn.getLastErrorText(alloc)});
        return;
    };

    // Convert ASN.1 to XML:
    const str_xml = asn.asnToXml(alloc) catch {
        std.debug.print("{s}\n", .{try asn.getLastErrorText(alloc)});
        return;
    };

    // The XML returned by AsnToXml will be compact and not pretty-formatted.
    // Use Chilkat XML to format the XML better:
    const xml = try chilkat.Xml.init();
    defer xml.deinit();
    try xml.loadXml(str_xml);
    // Assuming success for this example..
    // This is formatted better for human viewing:
    std.debug.print("{s}\n", .{try xml.getXml(alloc)});

    // Now get the ASN.1 in base64 format.  Any encoding supported
    // by Chilkat can be passed, such as "hex", "uu", "quoted-printable", "base32", "modbase64", etc.
    const str_base64 = try asn.getEncodedDer(alloc, "base64");

    // Load the ASN.1 from XML:
    const asn2 = try chilkat.Asn.init();
    defer asn2.deinit();
    asn2.loadAsnXml(try xml.getXml(alloc)) catch {
        std.debug.print("{s}\n", .{try asn2.getLastErrorText(alloc)});
        return;
    };

    // Load the ASN.1 from an encoded string, such as base64:
    const asn3 = try chilkat.Asn.init();
    defer asn3.deinit();
    asn3.loadEncoded(str_base64, "base64") catch {
        std.debug.print("{s}\n", .{try asn3.getLastErrorText(alloc)});
        return;
    };
}