diff --git a/include/libwebsockets/lws-misc.h b/include/libwebsockets/lws-misc.h index 9b8b7a943..b853a2c45 100644 --- a/include/libwebsockets/lws-misc.h +++ b/include/libwebsockets/lws-misc.h @@ -309,6 +309,19 @@ lws_json_simple_strcmp(const char *buf, size_t len, const char *name, const char LWS_VISIBLE LWS_EXTERN int lws_hex_to_byte_array(const char *h, uint8_t *dest, int max); +/** + * lws_hex_from_byte_array(): render byte array as hex char string + * + * \param src: incoming binary source array + * \param slen: length of src in bytes + * \param dest: array to fill with hex chars representing src + * \param len: max extent of dest + * + * This converts binary data of length slen at src, into a hex string at dest + * of maximum length len. Even if truncated, the result will be NUL-terminated. + */ +LWS_VISIBLE LWS_EXTERN void +lws_hex_from_byte_array(const uint8_t *src, size_t slen, char *dest, size_t len); /** * lws_hex_random(): generate len - 1 or - 2 characters of random ascii hex diff --git a/lib/core/libwebsockets.c b/lib/core/libwebsockets.c index b3be8e9c0..935f30d16 100644 --- a/lib/core/libwebsockets.c +++ b/lib/core/libwebsockets.c @@ -155,6 +155,22 @@ lws_hex_to_byte_array(const char *h, uint8_t *dest, int max) static char *hexch = "0123456789abcdef"; +void +lws_hex_from_byte_array(const uint8_t *src, size_t slen, char *dest, size_t len) +{ + char *end = &dest[len - 1]; + + while (slen-- && dest != end) { + uint8_t b = *src++; + *dest++ = hexch[b >> 4]; + if (dest == end) + break; + *dest++ = hexch[b & 0xf]; + } + + *dest = '\0'; +} + int lws_hex_random(struct lws_context *context, char *dest, size_t len) {