From: Shuanglei Tao Date: Fri, 28 Oct 2016 05:44:17 +0000 (+0800) Subject: base64_encode: do not use openssl anymore X-Git-Url: http://git.prime8.dev/?a=commitdiff_plain;h=a16fdfdbd47a5dca1a939d6e7aa56cbabf2939c8;p=ttyd.git base64_encode: do not use openssl anymore --- diff --git a/src/utils.c b/src/utils.c index e8e2430..f53b4b8 100644 --- a/src/utils.c +++ b/src/utils.c @@ -1,14 +1,11 @@ #define _GNU_SOURCE #include +#include #include #include #include -#include -#include -#include - // http://web.mit.edu/~svalente/src/kill/kill.c #ifdef __linux__ /* @@ -78,24 +75,29 @@ get_sig(const char *sig_name) { return -1; } +// https://github.com/darkk/redsocks/blob/master/base64.c char * base64_encode(const unsigned char *buffer, size_t length) { - BIO *bio, *b64; - BUF_MEM *bptr; - - b64 = BIO_new(BIO_f_base64()); - bio = BIO_new(BIO_s_mem()); - b64 = BIO_push(b64, bio); + static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + char *ret, *dst; + unsigned i_bits = 0; + int i_shift = 0; + int bytes_remaining = (int) length; - BIO_write(b64, buffer, (int) length); - BIO_flush(b64); - BIO_get_mem_ptr(b64, &bptr); + ret = dst = t_malloc((size_t) (((length + 2) / 3 * 4) + 1)); + while (bytes_remaining) { + i_bits = (i_bits << 8) + *buffer++; + bytes_remaining--; + i_shift += 8; - char *data = (char *) t_malloc(bptr->length); - memcpy(data, bptr->data, bptr->length - 1); - data[bptr->length - 1] = 0; - - BIO_free_all(b64); + do { + *dst++ = b64[(i_bits << 6 >> i_shift) & 0x3f]; + i_shift -= 6; + } while (i_shift > 6 || (bytes_remaining == 0 && i_shift > 0)); + } + while ((dst - ret) & 3) + *dst++ = '='; + *dst = '\0'; - return data; + return ret; } \ No newline at end of file