also looking at this
Harden encrypted mail storage, recovery, and forwarding
#8
50 files
+1701
-9001
| @@ -1,47 +0,0 @@ | ||
| 1 | /// Cross-platform CSPRNG that works on macOS, Linux, and other targets. | |
| 2 | const std = @import("std"); | |
| 3 | const builtin = @import("builtin"); | |
| 4 | ||
| 5 | /// Fill buffer with cryptographically secure random bytes. | |
| 6 | pub fn fill(buf: []u8) void { | |
| 7 | switch (builtin.os.tag) { | |
| 8 | .macos, .ios, .freebsd, .netbsd, .openbsd => { | |
| 9 | std.c.arc4random_buf(buf.ptr, buf.len); | |
| 10 | }, | |
| 11 | .linux => { | |
| 12 | // Use getrandom syscall directly (always available via kernel >= 3.17) | |
| 13 | const rc = std.os.linux.getrandom(buf.ptr, buf.len, 0); | |
| 14 | // Check for error: on Linux syscalls, error is indicated by | |
| 15 | // return value > max_usize - 4096 (i.e., negative errno) | |
| 16 | if (rc > std.math.maxInt(usize) - 4096) { | |
| 17 | // Fallback: read from /dev/urandom | |
| 18 | urandomFill(buf); | |
| 19 | } | |
| 20 | }, | |
| 21 | else => { | |
| 22 | // Fallback for other platforms | |
| 23 | urandomFill(buf); | |
| 24 | }, | |
| 25 | } | |
| 26 | } | |
| 27 | ||
| 28 | fn urandomFill(buf: []u8) void { | |
| 29 | const fd = std.posix.openat(std.posix.AT.FDCWD, "/dev/urandom", .{ .ACCMODE = .RDONLY }, 0) catch return; | |
| 30 | defer _ = std.c.close(fd); | |
| 31 | var pos: usize = 0; | |
| 32 | while (pos < buf.len) { | |
| 33 | const n = std.posix.read(fd, buf[pos..]) catch return; | |
| 34 | if (n == 0) return; | |
| 35 | pos += n; | |
| 36 | } | |
| 37 | } | |
| 38 | ||
| 39 | /// std.Random interface backed by this CSPRNG | |
| 40 | pub const csprng: std.Random = .{ | |
| 41 | .ptr = undefined, | |
| 42 | .fillFn = struct { | |
| 43 | fn f(_: *anyopaque, b: []u8) void { | |
| 44 | fill(b); | |
| 45 | } | |
| 46 | }.f, | |
| 47 | }; | |