Skip to content

Commit

Permalink
remove hash.zig
Browse files Browse the repository at this point in the history
fix
  • Loading branch information
jinzhongjia committed Jul 31, 2024
1 parent ae3f8fa commit 7cd8355
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 42 deletions.
40 changes: 0 additions & 40 deletions src/hash.zig

This file was deleted.

3 changes: 1 addition & 2 deletions src/install.zig
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const std = @import("std");
const builtin = @import("builtin");
const config = @import("config.zig");
const hash = @import("hash.zig");
const download = @import("download.zig");
const architecture = @import("architecture.zig");
const tools = @import("tools.zig");
Expand Down Expand Up @@ -116,7 +115,7 @@ pub fn from_version(version: []const u8) !void {
if (data.shasum) |actual_shasum| {
const computed_hash = try download.content(allocator, data.name, data.tarball.?);
if (computed_hash) |shasum| {
if (!hash.verify_hash(shasum, actual_shasum)) {
if (!tools.verify_hash(shasum, actual_shasum)) {
return error.HashMismatch;
}
}
Expand Down
39 changes: 39 additions & 0 deletions src/tools.zig
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const std = @import("std");
const builtin = @import("builtin");

const testing = std.testing;

var allocator: std.mem.Allocator = undefined;
var home_dir: []const u8 = undefined;

Expand Down Expand Up @@ -47,3 +49,40 @@ pub fn get_zvm_path_segment(tmp_allocator: std.mem.Allocator, segment: []const u
&[_][]const u8{ get_home(), ".zm", segment },
);
}

/// for verify hash
pub fn verify_hash(computed_hash: [32]u8, actual_hash_string: []const u8) bool {
if (actual_hash_string.len != 64) return false; // SHA256 hash should be 64 hex characters

var actual_hash_bytes: [32]u8 = undefined;
var i: usize = 0;

for (actual_hash_string) |char| {
const byte = switch (char) {
'0'...'9' => char - '0',
'a'...'f' => char - 'a' + 10,
'A'...'F' => char - 'A' + 10,
else => return false, // Invalid character in hash string
};

if (i % 2 == 0) {
actual_hash_bytes[i / 2] = byte << 4;
} else {
actual_hash_bytes[i / 2] |= byte;
}

i += 1;
}

return std.mem.eql(u8, computed_hash[0..], actual_hash_bytes[0..]);
}

test "verify_hash basic test" {
const sample_hash: [32]u8 = [_]u8{ 0x33, 0x9a, 0x89, 0xdc, 0x08, 0x73, 0x6b, 0x84, 0xc4, 0x75, 0x2b, 0x3d, 0xed, 0xdc, 0x0f, 0x2c, 0x71, 0xb5, 0x0b, 0x66, 0xa2, 0x68, 0x5f, 0x26, 0x77, 0x9c, 0xbb, 0xac, 0x46, 0x11, 0x1b, 0x68 };

var sample_hash_hex: [64]u8 = undefined;
_ = std.fmt.bufPrint(&sample_hash_hex, "{}", .{std.fmt.fmtSliceHexLower(sample_hash[0..])}) catch unreachable;

try testing.expect(verify_hash(sample_hash, &sample_hash_hex));
try testing.expect(!verify_hash(sample_hash, "incorrect_hash"));
}

0 comments on commit 7cd8355

Please sign in to comment.