2019-02-25 14:48:22 +01:00
|
|
|
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
|
2015-07-09 15:20:47 +02:00
|
|
|
|
2017-09-11 16:51:13 +02:00
|
|
|
#include "base/base64.hpp"
|
2015-12-18 16:03:57 +01:00
|
|
|
#include <openssl/bio.h>
|
|
|
|
#include <openssl/evp.h>
|
|
|
|
#include <openssl/buffer.h>
|
2015-07-09 15:20:47 +02:00
|
|
|
#include <sstream>
|
|
|
|
|
|
|
|
using namespace icinga;
|
|
|
|
|
2015-12-18 16:03:57 +01:00
|
|
|
String Base64::Encode(const String& input)
|
2015-07-09 15:20:47 +02:00
|
|
|
{
|
2015-12-18 16:03:57 +01:00
|
|
|
BIO *biomem = BIO_new(BIO_s_mem());
|
|
|
|
BIO *bio64 = BIO_new(BIO_f_base64());
|
|
|
|
BIO_push(bio64, biomem);
|
|
|
|
BIO_set_flags(bio64, BIO_FLAGS_BASE64_NO_NL);
|
|
|
|
BIO_write(bio64, input.CStr(), input.GetLength());
|
2016-01-18 09:41:52 +01:00
|
|
|
(void) BIO_flush(bio64);
|
2015-12-18 16:03:57 +01:00
|
|
|
|
|
|
|
char *outbuf;
|
|
|
|
long len = BIO_get_mem_data(biomem, &outbuf);
|
2015-07-09 15:20:47 +02:00
|
|
|
|
2015-12-18 16:03:57 +01:00
|
|
|
String ret = String(outbuf, outbuf + len);
|
|
|
|
BIO_free_all(bio64);
|
2016-01-15 10:11:52 +01:00
|
|
|
|
2015-12-18 16:03:57 +01:00
|
|
|
return ret;
|
2015-07-09 15:20:47 +02:00
|
|
|
}
|
|
|
|
|
2015-12-18 16:03:57 +01:00
|
|
|
String Base64::Decode(const String& input)
|
2015-07-09 15:20:47 +02:00
|
|
|
{
|
2015-12-18 16:03:57 +01:00
|
|
|
BIO *biomem = BIO_new_mem_buf(
|
2017-12-19 15:50:05 +01:00
|
|
|
const_cast<char*>(input.CStr()), input.GetLength());
|
2015-12-18 16:03:57 +01:00
|
|
|
BIO *bio64 = BIO_new(BIO_f_base64());
|
|
|
|
BIO_push(bio64, biomem);
|
|
|
|
BIO_set_flags(bio64, BIO_FLAGS_BASE64_NO_NL);
|
2015-07-09 15:20:47 +02:00
|
|
|
|
2018-01-04 09:07:03 +01:00
|
|
|
auto *outbuf = new char[input.GetLength()];
|
2017-12-13 12:54:14 +01:00
|
|
|
|
2016-01-13 08:33:27 +01:00
|
|
|
size_t len = 0;
|
|
|
|
int rc;
|
|
|
|
|
|
|
|
while ((rc = BIO_read(bio64, outbuf + len, input.GetLength() - len)) > 0)
|
2015-12-18 16:03:57 +01:00
|
|
|
len += rc;
|
2015-07-09 15:20:47 +02:00
|
|
|
|
2015-12-18 16:03:57 +01:00
|
|
|
String ret = String(outbuf, outbuf + len);
|
|
|
|
BIO_free_all(bio64);
|
2016-01-15 10:11:52 +01:00
|
|
|
delete [] outbuf;
|
|
|
|
|
2015-12-18 16:03:57 +01:00
|
|
|
if (ret.IsEmpty() && !input.IsEmpty())
|
|
|
|
throw std::invalid_argument("Not a valid base64 string");
|
2015-07-09 15:20:47 +02:00
|
|
|
|
2015-12-18 16:03:57 +01:00
|
|
|
return ret;
|
2015-07-09 15:20:47 +02:00
|
|
|
}
|