]> granicus.if.org Git - icinga2/blob - lib/base/base64.cpp
Merge pull request #7002 from Icinga/bugfix/check_network-percent-6155
[icinga2] / lib / base / base64.cpp
1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
2
3 #include "base/base64.hpp"
4 #include <openssl/bio.h>
5 #include <openssl/evp.h>
6 #include <openssl/buffer.h>
7 #include <sstream>
8
9 using namespace icinga;
10
11 String Base64::Encode(const String& input)
12 {
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);
19
20         char *outbuf;
21         long len = BIO_get_mem_data(biomem, &outbuf);
22
23         String ret = String(outbuf, outbuf + len);
24         BIO_free_all(bio64);
25
26         return ret;
27 }
28
29 String Base64::Decode(const String& input)
30 {
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);
36
37         auto *outbuf = new char[input.GetLength()];
38
39         size_t len = 0;
40         int rc;
41
42         while ((rc = BIO_read(bio64, outbuf + len, input.GetLength() - len)) > 0)
43                 len += rc;
44
45         String ret = String(outbuf, outbuf + len);
46         BIO_free_all(bio64);
47         delete [] outbuf;
48
49         if (ret.IsEmpty() && !input.IsEmpty())
50                 throw std::invalid_argument("Not a valid base64 string");
51
52         return ret;
53 }