diff options
Diffstat (limited to 'src/hash.c')
| -rw-r--r-- | src/hash.c | 71 |
1 files changed, 71 insertions, 0 deletions
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 <blake2.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +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; +} |
