Skip to content

std.crypto.hash: add a non-clobbering method to serialize the current hash value #13400

@nektro

Description

@nektro

Zig Version

0.11.0-dev.6+2943df016

Steps to Reproduce and Observed Behavior

const std = @import("std");

test {
    const Sha256 = std.crypto.hash.sha2.Sha256;
    const length = Sha256.digest_length;

    var b1: [length]u8 = undefined;
    var h1 = Sha256.init(.{});
    h1.update("abab");
    h1.update("cdcd");
    h1.final(&b1);
    h1.update("efef");
    h1.final(&b1);
    var o1: [length * 2]u8 = undefined;
    _ = try std.fmt.bufPrint(&o1, "{}", .{std.fmt.fmtSliceHexLower(&b1)});

    var b2: [length]u8 = undefined;
    var h2 = Sha256.init(.{});
    h2.update("abab");
    h2.update("cdcd");
    h2.update("efef");
    h2.final(&b2);
    var o2: [length * 2]u8 = undefined;
    _ = try std.fmt.bufPrint(&o2, "{}", .{std.fmt.fmtSliceHexLower(&b2)});

    try std.testing.expectEqualStrings(&o2, &o1);
}
Test [1/1] test_0... 
====== expected this output: =========
7a8abe2debd5bc4afc9a940226200962136858ad3bd4f2777ad2974f133f3237␃

======== instead found this: =========
6934c9d035b7387a84482e1f5c0c4f7ead3b2784ba3923630fc0f5aecee733a3␃

======================================
First difference occurs on line 1:
expected:
7a8abe2debd5bc4afc9a940226200962136858ad3bd4f2777ad2974f133f3237
^ ('\x37')
found:
6934c9d035b7387a84482e1f5c0c4f7ead3b2784ba3923630fc0f5aecee733a3
^ ('\x36')
Test [1/1] test_0... FAIL (TestExpectedEqual)

Expected Behavior

.final() to not dirty the state, or an alternate function (eg .serialize() that does not clobber)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behavior

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions