Skip to content

Commit 501399a

Browse files
committed
Feat/Hashers: Implement sha256d :fixes #3
1 parent ba12e8b commit 501399a

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

src/hashes/sha256d.zig

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
const std = @import("std");
2+
const Hash = std.crypto.sha256;
3+
4+
pub const HashEngine = struct {
5+
sha256_engine: Hash.Context,
6+
7+
pub fn new() HashEngine {
8+
return HashEngine{
9+
.sha256_engine = Hash.Context.init(),
10+
};
11+
}
12+
13+
pub fn input(self: *HashEngine, data: []const u8) void {
14+
self.sha256_engine.update(data);
15+
}
16+
17+
pub fn n_bytes_hashed(self: *const HashEngine) usize {
18+
return self.sha256_engine.total_len;
19+
}
20+
21+
pub fn final(self: *HashEngine) []u8 {
22+
var sha1_result: [32]u8 = undefined;
23+
self.sha256_engine.final(&sha1_result);
24+
25+
var sha2_result: [32]u8 = undefined;
26+
var second_sha256 = Hash.hash(sha1_result[0..]);
27+
std.mem.copy(u8, sha2_result[0..], second_sha256[0..]);
28+
29+
return sha2_result[0..];
30+
}
31+
};
32+
33+
// Test cases
34+
test "double SHA256 (SHA256d)" {
35+
const input = "hello world";
36+
var engine = HashEngine.new();
37+
engine.input(input);
38+
39+
const expected_hash: [32]u8 = [_]u8{ 0xb9, 0x4d, 0x27, 0xb9, 0x93, 0x4d, 0x3e, 0x08, 0xa5, 0x2e, 0x52, 0xd7, 0xda, 0x7d, 0xab, 0xfa, 0xc4, 0x6e, 0x0f, 0xf4, 0x78, 0x91, 0x87, 0x3c, 0xc8, 0x89, 0x3f, 0xbe, 0x58, 0x68, 0xb2, 0x38 };
40+
41+
const result = engine.final();
42+
43+
try std.testing.expect(std.mem.eql(u8, result, expected_hash));
44+
}
45+
46+
test "empty string double SHA256 (SHA256d)" {
47+
const input = "";
48+
var engine = HashEngine.new();
49+
engine.input(input);
50+
51+
const expected_hash: [32]u8 = [_]u8{ 0x5d, 0xf6, 0xe0, 0xe2, 0x76, 0x13, 0x59, 0xd3, 0x0a, 0x82, 0x75, 0x05, 0x8e, 0x29, 0x9f, 0xcc, 0x03, 0x81, 0x53, 0x45, 0x45, 0xf5, 0x5c, 0xf4, 0x3e, 0x41, 0x98, 0x3f, 0x5d, 0x4c, 0x94, 0x56 };
52+
53+
const result = engine.final();
54+
55+
try std.testing.expect(std.mem.eql(u8, result, expected_hash));
56+
}

0 commit comments

Comments
 (0)