From 2852ce468572b33b960776ea3440aa62acf7736b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milan=20=C5=A0pinka?= Date: Wed, 29 Jan 2025 23:24:14 +0100 Subject: [PATCH] Fix SHA-2 hash serialization. --- src/primitive/digest/sha_2.zig | 6 ++---- src/primitive/digest/sha_core.zig | 14 ++++++++++++-- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/primitive/digest/sha_2.zig b/src/primitive/digest/sha_2.zig index 4c7a9c1..5344bce 100644 --- a/src/primitive/digest/sha_2.zig +++ b/src/primitive/digest/sha_2.zig @@ -398,8 +398,7 @@ pub fn sha512_224_update(ctx: *Sha512Ctx, message: []const u8) !void { pub fn sha512_224_final(ctx: *Sha512Ctx, out: *[SHA_512_224_DIGEST_LENGTH]u8) void { if (dbg and !ctx.t_is_224) @panic("Debug: Attempt to call sha512_224_final on a SHA-2 context not initialized in 224-bit mode."); - sha512_context_final(ctx, SHA_512_224_DIGEST_LENGTH, out); - std.debug.print("{x}\n", .{ctx.hash}); + return sha512_context_final(ctx, SHA_512_224_DIGEST_LENGTH, out); } pub fn sha512_256_new() Sha512Ctx { @@ -415,8 +414,7 @@ pub fn sha512_256_update(ctx: *Sha512Ctx, message: []const u8) !void { pub fn sha512_256_final(ctx: *Sha512Ctx, out: *[SHA_512_256_DIGEST_LENGTH]u8) void { if (dbg and !ctx.t_is_256) @panic("Debug: Attempt to call sha512_256_final on a SHA-2 context not initialized in 256-bit mode."); - sha512_context_final(ctx, SHA_512_256_DIGEST_LENGTH, out); - std.debug.print("{x}\n", .{ctx.hash}); + return sha512_context_final(ctx, SHA_512_256_DIGEST_LENGTH, out); } // https://www.di-mgt.com.au/sha_testvectors.html diff --git a/src/primitive/digest/sha_core.zig b/src/primitive/digest/sha_core.zig index b3fea46..20c39ef 100644 --- a/src/primitive/digest/sha_core.zig +++ b/src/primitive/digest/sha_core.zig @@ -101,9 +101,19 @@ pub fn generic_final( // Serialize the result. const word_size = @typeInfo(WordType).Int.bits / 8; - for (0..digest_length / word_size) |w| { + var serialized_bytes: usize = 0; + for (0..ctx.hash.len) |w| { const serialized_word = serialize_int_big_endian(WordType, ctx.hash[w]); - @memcpy(out[(w * word_size)..((w + 1) * word_size)], serialized_word[0..]); + + // The digest_length does not have to be a multiple of word_size! + if (serialized_bytes > digest_length - word_size) { + @memcpy(out[w * word_size ..], serialized_word[0..(digest_length - serialized_bytes)]); + serialized_bytes += word_size; + break; + } else { + @memcpy(out[(w * word_size)..((w + 1) * word_size)], serialized_word[0..]); + serialized_bytes += word_size; + } } }