Skip to content

Commit e579c88

Browse files
committed
std.crypto.siphash: add finalResult() and peek()
Useful for avoiding mutable state when using this API.
1 parent 87b2234 commit e579c88

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

lib/std/crypto/siphash.zig

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,11 @@ fn SipHashStateless(comptime T: type, comptime c_rounds: usize, comptime d_round
8787
self.msg_len +%= @truncate(u8, b.len);
8888
}
8989

90+
pub fn peek(self: Self) [digest_length]u8 {
91+
var copy = self;
92+
return copy.finalResult();
93+
}
94+
9095
pub fn final(self: *Self, b: []const u8) T {
9196
std.debug.assert(b.len < 8);
9297

@@ -124,6 +129,12 @@ fn SipHashStateless(comptime T: type, comptime c_rounds: usize, comptime d_round
124129
return (@as(u128, b2) << 64) | b1;
125130
}
126131

132+
pub fn finalResult(self: *Self) [digest_length]u8 {
133+
var result: [digest_length]u8 = undefined;
134+
self.final(&result);
135+
return result;
136+
}
137+
127138
fn round(self: *Self, b: [8]u8) void {
128139
const m = mem.readIntLittle(u64, b[0..8]);
129140
self.v3 ^= m;
@@ -205,12 +216,23 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize)
205216
self.buf_len += @intCast(u8, b[off + aligned_len ..].len);
206217
}
207218

219+
pub fn peek(self: Self) [mac_length]u8 {
220+
var copy = self;
221+
return copy.finalResult();
222+
}
223+
208224
/// Return an authentication tag for the current state
209225
/// Assumes `out` is less than or equal to `mac_length`.
210226
pub fn final(self: *Self, out: *[mac_length]u8) void {
211227
mem.writeIntLittle(T, out, self.state.final(self.buf[0..self.buf_len]));
212228
}
213229

230+
pub fn finalResult(self: *Self) [mac_length]u8 {
231+
var result: [mac_length]u8 = undefined;
232+
self.final(&result);
233+
return result;
234+
}
235+
214236
/// Return an authentication tag for a message and a key
215237
pub fn create(out: *[mac_length]u8, msg: []const u8, key: *const [key_length]u8) void {
216238
var ctx = Self.init(key);

0 commit comments

Comments
 (0)