Sample code for 30+ languages & platforms
Zig Requires Chilkat v11.6.0+

Hash a Password with Argon2 (Tuned Options)

Demonstrates Crypt2.Argon2HashPassword with explicit options: the cost parameters, saltLen (how many random salt bytes to generate when no salt is given), and an optional secret (pepper).

Background. For hashing, the salt is optional — when omitted, a random salt of saltLen bytes (default 16) is generated, which is the normal case. A secret or ad is not stored in the PHC string; the same values must be supplied to Argon2VerifyPassword for the password to verify.

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

    // The password should come from a secure source rather than being hard-coded.
    const password = "correct horse battery staple";

    // The Argon2 options are the same members as Argon2DeriveKey, except the salt is optional for
    // hashing.  When no "salt" is given, a random salt is generated; "saltLen" (default 16, range 8..1024)
    // sets how many random bytes to use.
    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    json.updateString("variant", "argon2id") catch {};
    json.updateInt("memoryCostKb", 131072) catch {};
    json.updateInt("iterations", 4) catch {};
    json.updateInt("parallelism", 2) catch {};
    json.updateInt("saltLen", 16) catch {};

    // A secret (pepper) and/or ad may be used, but neither is stored in the returned PHC string.  The
    // same values must be supplied to Argon2VerifyPassword for the password to verify.
    json.updateString("secret", "application-wide-pepper") catch {};
    json.updateString("secretEncoding", "utf-8") catch {};

    const phc_hash = crypt.argon2HashPassword(alloc, password, try json.emit(alloc)) catch {
        std.debug.print("{s}\n", .{try crypt.getLastErrorText(alloc)});
        return;
    };

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