Sample code for 30+ languages & platforms
Zig

Example: Hash Text in Chunks

Shows how to generate a final hash, like SHA-256, for a large text by processing it in chunks.

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 crypt = try chilkat.Crypt2.init();
    defer crypt.deinit();
    crypt.setHashAlgorithm("sha256");
    crypt.setCharset("utf-8");

    const bd = try chilkat.BinData.init();
    defer bd.deinit();

    const s = "The quick brown fox jumped over the lazy dog.\r\n";

    // Accumulate the text in a StringBuilder.  We'll demonstrate hashing the text in chunks,
    // and then also hashing the entire text at once to show the results are the same.

    bd.appendString(s, "utf-8") catch {};
    try crypt.hashBeginString(s);

    var i: i32 = 0;
    while (i < 200) {
        bd.appendString(s, "utf-8") catch {};
        crypt.hashMoreString(s) catch {};
        i = i + 1;
    }

    // Get the hash in base64 format.
    crypt.setEncodingMode("base64");

    var encoded_hash: [:0]const u8 = try crypt.hashFinalENC(alloc);
    std.debug.print("Hash computed in chunks: {s}\n", .{encoded_hash});

    // Let's alternatively compute the hash of the entire amount of data at once,
    // to show the hash computation is the same:
    encoded_hash = try crypt.hashBdENC(alloc, bd);
    std.debug.print("Hash computed in 1 step: {s}\n", .{encoded_hash});

    // Output:

    // Hash computed in chunks: unwkVff61k40roRIJizaknreScHaL6frWe37kydXbZQ=
    // Hash computed in 1 step: unwkVff61k40roRIJizaknreScHaL6frWe37kydXbZQ=
}