hash.c (2596B)
1 // Hash CLI {{{ 2 // 3 // Exposes the sfinx hash wrappers to the openssl anchor test 4 // hash <224|256|384|512> read stdin, print the SHA3 hex 5 // hash shake <bytes> read stdin, print the SHAKE256 hex 6 // This is the only place the wrappers and openssl meet 7 8 #include <stdint.h> 9 #include <stdio.h> 10 #include <stdlib.h> 11 #include <string.h> 12 13 #include "src/sfinx.c" 14 15 static void print_hex(const uint8_t *in, size_t len) { 16 static const char digits[] = "0123456789abcdef"; 17 for (size_t i = 0; i < len; i++) { 18 putchar(digits[in[i] >> 4]); 19 putchar(digits[in[i] & 0x0f]); 20 } 21 putchar('\n'); 22 } 23 24 static int read_stdin(uint8_t **out, size_t *out_len) { 25 size_t cap = 4096; 26 size_t len = 0; 27 uint8_t *buf = malloc(cap); 28 if (!buf) { 29 return 0; 30 } 31 for (;;) { 32 if (len == cap) { 33 size_t next_cap = cap * 2; 34 uint8_t *next = realloc(buf, next_cap); 35 if (!next) { 36 free(buf); 37 return 0; 38 } 39 buf = next; 40 cap = next_cap; 41 } 42 len += fread(buf + len, 1, cap - len, stdin); 43 if (feof(stdin)) { 44 break; 45 } 46 } 47 *out = buf; 48 *out_len = len; 49 return 1; 50 } 51 52 int main(int argc, char **argv) { 53 uint8_t *in = NULL; 54 size_t in_len = 0; 55 56 if (argc == 3 && strcmp(argv[1], "shake") == 0) { 57 char *end = NULL; 58 long out_len = strtol(argv[2], &end, 10); 59 uint8_t *out; 60 if (!end || *end != '\0' || out_len < 0 || out_len > (1 << 20)) { 61 fprintf(stderr, "usage: hash shake <bytes>\n"); 62 return 2; 63 } 64 if (!read_stdin(&in, &in_len)) { 65 fprintf(stderr, "hash: out of memory\n"); 66 return 2; 67 } 68 out = malloc((size_t)out_len > 0 ? (size_t)out_len : 1); 69 if (!out) { 70 free(in); 71 fprintf(stderr, "hash: out of memory\n"); 72 return 2; 73 } 74 _sfinx_shake256(in, in_len, out, (size_t)out_len); 75 print_hex(out, (size_t)out_len); 76 free(out); 77 free(in); 78 return 0; 79 } 80 81 if (argc == 2) { 82 char *end = NULL; 83 long bits = strtol(argv[1], &end, 10); 84 sfinx_hash hash = (sfinx_hash)bits; 85 uint8_t out[SFINX_HASH_LEN_MAX]; 86 if (!end || *end != '\0' || sfinx_hash_len(hash) == 0) { 87 fprintf(stderr, "usage: hash <224|256|384|512>\n"); 88 return 2; 89 } 90 if (!read_stdin(&in, &in_len)) { 91 fprintf(stderr, "hash: out of memory\n"); 92 return 2; 93 } 94 _sfinx_hash(hash, in, in_len, out); 95 print_hex(out, sfinx_hash_len(hash)); 96 free(in); 97 return 0; 98 } 99 100 fprintf(stderr, "usage: hash <224|256|384|512>\n hash shake <bytes>\n"); 101 return 2; 102 } 103 // }}} 104 105 // vim:fdm=marker:fdl=0