Skip to content

Commit b827821

Browse files
argon2id password hash (#113)
Hello, I want to add this example in the section of Cryptography. As the 'Argon2' is a powerful and popular algorithms, I think adding this would be really helpful for all zig learners. --------- Co-authored-by: Jiacai Liu <[email protected]>
1 parent 662a3c7 commit b827821

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

assets/src/02-03.zig

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
const std = @import("std");
2+
3+
pub fn main() !void {
4+
var dbg = std.heap.DebugAllocator(.{}){};
5+
defer _ = dbg.deinit();
6+
const allocator = dbg.allocator();
7+
8+
const password = "happy";
9+
10+
//Random salt (Must be at least 8 bytes, recommended 16+)
11+
var raw: [8]u8 = undefined;
12+
std.crypto.random.bytes(&raw);
13+
const salt = try std.fmt.allocPrint(allocator, "{s}", .{std.fmt.bytesToHex(raw, .lower)});
14+
defer allocator.free(salt);
15+
16+
//Parameters for Argon2id
17+
const params = std.crypto.pwhash.argon2.Params{
18+
.t = 3, // Iterations (time cost)
19+
.m = 16, // Memory cost in KiB (here 16 MiB)
20+
.p = 1, // Threads
21+
};
22+
23+
const dk_len: usize = 16; // derive 16 or 32-byte key
24+
var derived: [dk_len]u8 = undefined;
25+
26+
try std.crypto.pwhash.argon2.kdf(
27+
allocator,
28+
&derived,
29+
password,
30+
salt,
31+
params,
32+
.argon2id, //argon2i, argon2d and argon2id
33+
);
34+
35+
std.debug.print("Argon2id derived key: {s}\n", .{std.fmt.bytesToHex(derived, .lower)});
36+
}

src/en-US/02-03-argon2.smd

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
.title = "Salt and hash a password with Argon2",
3+
.date = "2025-08-28",
4+
.author = "ZigCC",
5+
.layout = "section.shtml",
6+
---
7+
Salt and hash a password with Argon2
8+
9+
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`].
10+
11+
[]($code.siteAsset('src/02-03.zig').language('zig'))
12+
13+
[`std.crypto.pwhash.argon2`]: https://ziglang.org/documentation/0.14.0/std/#std.crypto.pwhash.argon2
14+
[`std.crypto.random`]: https://ziglang.org/documentation/0.14.0/std/#std.crypto.tlcsprng.interface

src/en-US/toc.smd

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

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

2324
- Date and Time
2425

0 commit comments

Comments
 (0)