From e06c72e4830de9143d66ddcc74440b5854d70bb1 Mon Sep 17 00:00:00 2001 From: Con Kolivas Date: Fri, 11 Apr 2014 09:38:01 +1000 Subject: [PATCH] Add a helper function for encoding into mime base64 --- src/libckpool.c | 53 +++++++++++++++++++++++++++++++++++++++++++++++++ src/libckpool.h | 1 + 2 files changed, 54 insertions(+) diff --git a/src/libckpool.c b/src/libckpool.c index 2fb53253..b7855824 100644 --- a/src/libckpool.c +++ b/src/libckpool.c @@ -370,6 +370,59 @@ void b58tobin(uchar *b58bin, const uchar *b58) } } +static const char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +/* Return a malloced string of *src encoded into mime base 64 */ +uchar *http_base64(const uchar *src) +{ + uchar *str, *dst; + size_t l, hlen; + int t, r; + + l = strlen((const char *)src); + hlen = ((l + 2) / 3) * 4 + 1; + align_len(&hlen); + str = malloc(hlen); + if (unlikely(!str)) + return str; + dst = str; + r = 0; + + while (l >= 3) { + t = (src[0] << 16) | (src[1] << 8) | src[2]; + dst[0] = base64[(t >> 18) & 0x3f]; + dst[1] = base64[(t >> 12) & 0x3f]; + dst[2] = base64[(t >> 6) & 0x3f]; + dst[3] = base64[(t >> 0) & 0x3f]; + src += 3; l -= 3; + dst += 4; r += 4; + } + + switch (l) { + case 2: + t = (src[0] << 16) | (src[1] << 8); + dst[0] = base64[(t >> 18) & 0x3f]; + dst[1] = base64[(t >> 12) & 0x3f]; + dst[2] = base64[(t >> 6) & 0x3f]; + dst[3] = '='; + dst += 4; + r += 4; + break; + case 1: + t = src[0] << 16; + dst[0] = base64[(t >> 18) & 0x3f]; + dst[1] = base64[(t >> 12) & 0x3f]; + dst[2] = dst[3] = '='; + dst += 4; + r += 4; + break; + case 0: + break; + } + *dst = 0; + return (str); +} + void address_to_pubkeytxn(uchar *pkh, const uchar *addr) { uchar b58bin[25]; diff --git a/src/libckpool.h b/src/libckpool.h index 9927da61..d36bdb22 100644 --- a/src/libckpool.h +++ b/src/libckpool.h @@ -116,6 +116,7 @@ void align_len(size_t *len); void __bin2hex(uchar *s, const uchar *p, size_t len); void *bin2hex(const uchar *p, size_t len); bool hex2bin(uchar *p, const uchar *hexstr, size_t len); +uchar *http_base64(const uchar *src); void b58tobin(uchar *b58bin, const uchar *b58); void address_to_pubkeytxn(uchar *pkh, const uchar *addr); int ser_number(uchar *s, int32_t val);