From b8300c0b6ee7767cfd7a23df266ba76e8521a394 Mon Sep 17 00:00:00 2001 From: Jussi Kuokkanen Date: Sun, 1 Dec 2019 13:53:07 +0200 Subject: [PATCH] lib: add SHA256 functions --- src/include/tc_common.h | 5 ++++- src/lib/tc_common.c | 17 ++++++++++++++++- src/lib/tc_readable.c | 3 ++- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/include/tc_common.h b/src/include/tc_common.h index 504f809..806ef5f 100644 --- a/src/include/tc_common.h +++ b/src/include/tc_common.h @@ -59,10 +59,13 @@ typedef struct tc_bin_node_ { // Create a new node with key and data in the appropriate position tc_bin_node_t *tc_bin_node_insert(tc_bin_node_t* node, void *key, void *value); // Find the value associated with the key -void *tc_bin_node_find_value(tc_bin_node_t *node, void *key); +void *tc_bin_node_find_value(tc_bin_node_t *node, const void *key); // Destroy a node and its children void tc_bin_node_destroy(tc_bin_node_t *node); +// Function for const char* -> SHA256. Don't free(). +const char *tc_sha256(const char *string, uint32_t string_length); + #ifdef __cplusplus } #endif diff --git a/src/lib/tc_common.c b/src/lib/tc_common.c index 22a8b2f..8df21d3 100644 --- a/src/lib/tc_common.c +++ b/src/lib/tc_common.c @@ -1,8 +1,11 @@ #include #include +#include #include +#include + char **tc_str_arr_dup(uint16_t str_count, char **const strings) { char **ptr_arr = calloc(str_count, sizeof(char*)); for (uint16_t i = 0; i < str_count; i++) { @@ -54,7 +57,7 @@ tc_bin_node_t *tc_bin_node_insert(tc_bin_node_t *node, void *key, void *value) { return node; } -void *tc_bin_node_find_value(tc_bin_node_t *node, void *key) { +void *tc_bin_node_find_value(tc_bin_node_t *node, const void *key) { if (node == NULL) { return NULL; } @@ -71,3 +74,15 @@ void *tc_bin_node_find_value(tc_bin_node_t *node, void *key) { void tc_bin_node_destroy(tc_bin_node_t *node) { traverse_postorder(node, &single_destroy); } + +const char *tc_sha256(const char *string, uint32_t string_length) { + unsigned char *d = SHA256((unsigned char*) string, string_length, 0); + + static char out[(SHA256_DIGEST_LENGTH * 2) + 1]; + + for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) { + sprintf(out + (i * 2), "%02x", d[i]); + } + out[SHA256_DIGEST_LENGTH * 2] = '\0'; + return out; +} diff --git a/src/lib/tc_readable.c b/src/lib/tc_readable.c index ea469c0..de76c08 100644 --- a/src/lib/tc_readable.c +++ b/src/lib/tc_readable.c @@ -66,8 +66,9 @@ tc_readable_result_t tc_readable_result_create(enum tc_data_types type, void *da break; case TC_TYPE_INT: res.data.int_value = *(int64_t*) data; + break; case TC_TYPE_DOUBLE: - res.data.uint_value = *(double*) data; + res.data.double_value = *(double*) data; break; default: res.valid = false;