authorgravatar for hello@nektro.netMeghan <hello@nektro.net> 2021-01-09 17:02:21 -08:00
committergravatar for hello@nektro.netMeghan <hello@nektro.net> 2021-01-09 17:02:21 -08:00
logf1c68f9abc97751be37a7bb0ffdb89521f4a13a8
tree33252f5db97b74ad949fda4db12d10089743b7ce
parent74026e975f172fa0f90c5ff3d15aacd692f708b7

util: dry up validate_hash


1 files changed, 16 insertions(+), 23 deletions(-)

src/util/funcs.zig+16-23
......@@ -261,27 +261,20 @@ pub fn validate_hash(input: []const u8, file_path: []const u8) !bool {
261261 const file = try std.fs.cwd().openFile(file_path, .{});
262262 defer file.close();
263263 const data = try file.reader().readAllAlloc(gpa, gb);
264 return std.mem.eql(u8, hash.string, switch (hash.id) {
265 .blake3 => blk: {
266 const h = &std.crypto.hash.Blake3.init(.{});
267 var out: [32]u8 = undefined;
268 h.update(data);
269 h.final(&out);
270 break :blk try std.fmt.allocPrint(gpa, "{x}", .{out});
271 },
272 .sha256 => blk: {
273 const h = &std.crypto.hash.sha2.Sha256.init(.{});
274 var out: [32]u8 = undefined;
275 h.update(data);
276 h.final(&out);
277 break :blk try std.fmt.allocPrint(gpa, "{x}", .{out});
278 },
279 .sha512 => blk: {
280 const h = &std.crypto.hash.sha2.Sha512.init(.{});
281 var out: [64]u8 = undefined;
282 h.update(data);
283 h.final(&out);
284 break :blk try std.fmt.allocPrint(gpa, "{x}", .{out});
285 },
286 });
264 const expected = hash.string;
265 const actual = switch (hash.id) {
266 .blake3 => try do_hash(std.crypto.hash.Blake3, data),
267 .sha256 => try do_hash(std.crypto.hash.sha2.Sha256, data),
268 .sha512 => try do_hash(std.crypto.hash.sha2.Sha512, data),
269 };
270 return std.mem.eql(u8, expected, actual);
271}
272
273pub fn do_hash(comptime algo: type, data: []const u8) ![]const u8 {
274 const h = &algo.init(.{});
275 var out: [algo.digest_length]u8 = undefined;
276 h.update(data);
277 h.final(&out);
278 const hex = try std.fmt.allocPrint(gpa, "{x}", .{out});
279 return hex;
287280}