From d57e02626d46e4aa20aae8c01d57468720917975 Mon Sep 17 00:00:00 2001 From: Koichiro IWAO Date: Thu, 22 Jun 2017 14:25:34 +0900 Subject: [PATCH] add base64_decode function --- common/ssl_calls.c | 54 ++++++++++++++++++++++++++++++++++++++++++++++ common/ssl_calls.h | 4 ++++ 2 files changed, 58 insertions(+) diff --git a/common/ssl_calls.c b/common/ssl_calls.c index 0e12e960..d43ed873 100644 --- a/common/ssl_calls.c +++ b/common/ssl_calls.c @@ -32,6 +32,8 @@ #include #include #include +#include /* needed for base64 */ +#include /* needed for base64 */ #include "os_calls.h" #include "arch.h" @@ -930,3 +932,55 @@ ssl_get_protocols_from_string(const char *str, long *ssl_protocols) return rv; } +/*****************************************************************************/ +size_t +base64_decoded_bytes(const char *src) +{ + size_t len; + size_t padding; + + len = g_strlen(src); + padding = 0; + + if (src[len - 1] == '=') + { + padding++; + + if (src[len - 2] == '=') + { + padding++; + } + } + + return len * 3 / 4 - padding; +} + +/*****************************************************************************/ +char * +base64_decode(char *dst, const char *src, size_t len) +{ + BIO *b64; + BIO *bio; + char *b64str; + size_t estimated_decoded_bytes; + size_t decoded_bytes; + + b64str = g_strdup(src); + estimated_decoded_bytes = base64_decoded_bytes(b64str); + dst[estimated_decoded_bytes] = '\0'; + + b64 = BIO_new(BIO_f_base64()); + bio = BIO_new_mem_buf(b64str, len); + bio = BIO_push(b64, bio); + BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL); + decoded_bytes = BIO_read(bio , dst, len); + BIO_free_all(bio); + + /* if input is corrupt, return empty string */ + if (estimated_decoded_bytes != decoded_bytes) + { + g_strncpy(dst, "", sizeof("")); + } + + return dst; +} diff --git a/common/ssl_calls.h b/common/ssl_calls.h index dc60a23e..a957b994 100644 --- a/common/ssl_calls.h +++ b/common/ssl_calls.h @@ -114,5 +114,9 @@ const char * ssl_get_cipher_name(const struct ssl_st *ssl); int ssl_get_protocols_from_string(const char *str, long *ssl_protocols); +size_t +base64_decoded_bytes(const char *src); +char * +base64_decode(char *dst, const char *src, size_t len); #endif