Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions assets/src/02-03.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const std = @import("std");

pub fn main() !void {
var dbg = std.heap.DebugAllocator(.{}){};
defer _ = dbg.deinit();
const allocator = dbg.allocator();

const password = "happy";

//Random salt (Must be at least 8 bytes, recommended 16+)
var raw: [8]u8 = undefined;
std.crypto.random.bytes(&raw);
const salt = try std.fmt.allocPrint(allocator, "{s}", .{std.fmt.bytesToHex(raw, .lower)});
defer allocator.free(salt);

//Parameters for Argon2id
const params = std.crypto.pwhash.argon2.Params{
.t = 3, // Iterations (time cost)
.m = 16, // Memory cost in KiB (here 16 MiB)
.p = 1, // Threads
};

const dk_len: usize = 16; // derive 16 or 32-byte key
var derived: [dk_len]u8 = undefined;

try std.crypto.pwhash.argon2.kdf(
allocator,
&derived,
password,
salt,
params,
.argon2id, //argon2i, argon2d and argon2id
);

std.debug.print("Argon2id derived key: {s}\n", .{std.fmt.bytesToHex(derived, .lower)});
}
14 changes: 14 additions & 0 deletions src/en-US/02-03-argon2.smd
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
.title = "Salt and hash a password with Argon2",
.date = "2025-08-28",
.author = "ZigCC",
.layout = "section.shtml",
---
Salt and hash a password with Argon2

This Zig program derives a cryptographic key from a password and salt using the Argon2id password hashing algorithm. It uses [std.crypto.pwhash.argon2] to hash a salted password, where the salt is generated using [`std.crypto.random`].

[]($code.siteAsset('src/02-03.zig').language('zig'))

[`std.crypto.pwhash.argon2`]: https://ziglang.org/documentation/0.14.0/std/#std.crypto.pwhash.argon2
[`std.crypto.random`]: https://ziglang.org/documentation/0.14.0/std/#std.crypto.tlcsprng.interface
1 change: 1 addition & 0 deletions src/en-US/toc.smd
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

- [Calculate SHA-256 digest of a file](02-01-sha-digest)
- [Salt and hash a password with PBKDF2](02-02-pbkdf2)
- [Salt and hash a password with Argon2](02-03-argon2)

- Date and Time

Expand Down
Loading