Fix SHA-2 hash serialization.

This commit is contained in:
Milan Špinka
2025-01-29 23:24:14 +01:00
parent 465273892c
commit 2852ce4685
2 changed files with 14 additions and 6 deletions

View File

@ -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

View File

@ -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;
}
}
}