From 3b4f3014683a439dd7f0d1e663743cf0641a05c1 Mon Sep 17 00:00:00 2001 From: forever2k38 Date: Mon, 7 Sep 2026 15:53:21 +0200 Subject: hash verification --- src/hash.c | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 src/hash.c (limited to 'src/hash.c') diff --git a/src/hash.c b/src/hash.c new file mode 100644 index 0000000..2cb0851 --- /dev/null +++ b/src/hash.c @@ -0,0 +1,71 @@ +#include "hash.h" + +#include +#include +#include +#include +#include + +int pow_check_blake2b_hash(char *path, char *target_hash) { + FILE *fp = fopen(path, "rb"); + + if (!fp) { + printf("failed to open file to check hash\n"); + + return 1; + } + + fseek(fp, 0, SEEK_END); + long fsize = ftell(fp); + fseek(fp, 0, SEEK_SET); + + if (fsize < 0) { + printf("error: ftell\n"); + + fclose(fp); + + return 1; + } + + char *buf = NULL; + + if (fsize > 0) { + buf = malloc((size_t)fsize); + + if (!buf) { + fprintf(stderr, "out of memory\n"); + fclose(fp); + return 1; + } + + if (fread(buf, 1, (size_t)fsize, fp) != (size_t)fsize) { + fprintf(stderr, "read error\n"); + free(buf); + fclose(fp); + return 1; + } + } + + fclose(fp); + + uint8_t digest[BLAKE2B_OUTBYTES]; + if (blake2b(digest, buf, NULL, BLAKE2B_OUTBYTES, (size_t)fsize, 0) != 0) { + fprintf(stderr, "blake2b failed\n"); + free(buf); + return 1; + } + + free(buf); + + char hex[BLAKE2B_OUTBYTES * 2 + 1]; + for (size_t i = 0; i < BLAKE2B_OUTBYTES; i++) { + snprintf(&hex[i * 2], 3, "%02x", digest[i]); + } + hex[BLAKE2B_OUTBYTES * 2] = '\0'; + + if (!target_hash || strcmp(hex, target_hash) != 0) { + return 1; + } + + return 0; +} -- cgit v1.3