1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
3 #include "base/base64.hpp"
4 #include <openssl/bio.h>
5 #include <openssl/evp.h>
6 #include <openssl/buffer.h>
9 using namespace icinga;
11 String Base64::Encode(const String& input)
13 BIO *biomem = BIO_new(BIO_s_mem());
14 BIO *bio64 = BIO_new(BIO_f_base64());
15 BIO_push(bio64, biomem);
16 BIO_set_flags(bio64, BIO_FLAGS_BASE64_NO_NL);
17 BIO_write(bio64, input.CStr(), input.GetLength());
18 (void) BIO_flush(bio64);
21 long len = BIO_get_mem_data(biomem, &outbuf);
23 String ret = String(outbuf, outbuf + len);
29 String Base64::Decode(const String& input)
31 BIO *biomem = BIO_new_mem_buf(
32 const_cast<char*>(input.CStr()), input.GetLength());
33 BIO *bio64 = BIO_new(BIO_f_base64());
34 BIO_push(bio64, biomem);
35 BIO_set_flags(bio64, BIO_FLAGS_BASE64_NO_NL);
37 auto *outbuf = new char[input.GetLength()];
42 while ((rc = BIO_read(bio64, outbuf + len, input.GetLength() - len)) > 0)
45 String ret = String(outbuf, outbuf + len);
49 if (ret.IsEmpty() && !input.IsEmpty())
50 throw std::invalid_argument("Not a valid base64 string");