From 0408b8d499658c847b826e14976f0809658cdbc9 Mon Sep 17 00:00:00 2001 From: Evan Burkey Date: Fri, 29 Mar 2024 07:18:01 -0700 Subject: [PATCH] add hex_to_str --- docs/crypto.md | 9 +++++++++ include/lfcrypto.h | 2 ++ src/crypto.c | 9 +++++++++ tests/tests.c | 8 ++++++++ 4 files changed, 28 insertions(+) diff --git a/docs/crypto.md b/docs/crypto.md index 33714eb..624d27f 100644 --- a/docs/crypto.md +++ b/docs/crypto.md @@ -56,4 +56,13 @@ for (size_t i = 0; i < 4; ++i) { assert(s[i] == h[i]); } free(s); +``` + +### hex_to_str + +Converts an array of `unsigned char` into a string based on the ASCII values of each byte. User is +responsible for freeing the returned string. + +```c +const char *hex_to_str(const unsigned char *hex, size_t sz); ``` \ No newline at end of file diff --git a/include/lfcrypto.h b/include/lfcrypto.h index 0771811..7ba54ec 100644 --- a/include/lfcrypto.h +++ b/include/lfcrypto.h @@ -5,7 +5,9 @@ const char *b64_encode(const unsigned char *s, size_t sz); unsigned char *b64_decode(const char *s, size_t sz, size_t *decode_sz); + const char *hex_encode(const unsigned char *hex, size_t sz); unsigned char *hex_decode(const char *orig, size_t *sz); +const char *hex_to_str(const unsigned char *hex, size_t sz); #endif // LIBFLINT_CRYPTO_H diff --git a/src/crypto.c b/src/crypto.c index 0286f8c..7c332bf 100644 --- a/src/crypto.c +++ b/src/crypto.c @@ -243,3 +243,12 @@ const char *hex_encode(const unsigned char *hex, size_t sz) { return s; } + +const char *hex_to_str(const unsigned char *hex, size_t sz) { + char *s = malloc(sizeof(char) * (sz + 1)); + for (size_t i = 0; i < sz; ++i) { + s[i] = (char)hex[i]; + } + s[sz] = '\0'; + return s; +} \ No newline at end of file diff --git a/tests/tests.c b/tests/tests.c index 5193efa..bcbca01 100644 --- a/tests/tests.c +++ b/tests/tests.c @@ -349,6 +349,14 @@ void test_crypto() { s = hex_encode(h, 4); assert(strcmp(s, "DEADBEEF") == 0); free(s); + + // "Sup?" + unsigned char hexsup[4] = { + 0x53, 0x75, 0x70, 0x3F + }; + s = hex_to_str(hexsup, 4); + assert(strcmp(s, "Sup?") == 0); + free(s); } #if defined(__APPLE__) || defined(__MACH__)