summaryrefslogtreecommitdiffstats
path: root/lib/base/base64.cpp
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-13 11:32:39 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-13 11:32:39 +0000
commit56ae875861ab260b80a030f50c4aff9f9dc8fff0 (patch)
tree531412110fc901a5918c7f7442202804a83cada9 /lib/base/base64.cpp
parentInitial commit. (diff)
downloadicinga2-56ae875861ab260b80a030f50c4aff9f9dc8fff0.tar.xz
icinga2-56ae875861ab260b80a030f50c4aff9f9dc8fff0.zip
Adding upstream version 2.14.2.upstream/2.14.2upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'lib/base/base64.cpp')
-rw-r--r--lib/base/base64.cpp53
1 files changed, 53 insertions, 0 deletions
diff --git a/lib/base/base64.cpp b/lib/base/base64.cpp
new file mode 100644
index 0000000..42999c3
--- /dev/null
+++ b/lib/base/base64.cpp
@@ -0,0 +1,53 @@
+/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
+
+#include "base/base64.hpp"
+#include <openssl/bio.h>
+#include <openssl/evp.h>
+#include <openssl/buffer.h>
+#include <sstream>
+
+using namespace icinga;
+
+String Base64::Encode(const String& input)
+{
+ 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());
+ (void) BIO_flush(bio64);
+
+ char *outbuf;
+ long len = BIO_get_mem_data(biomem, &outbuf);
+
+ String ret = String(outbuf, outbuf + len);
+ BIO_free_all(bio64);
+
+ return ret;
+}
+
+String Base64::Decode(const String& input)
+{
+ BIO *biomem = BIO_new_mem_buf(
+ const_cast<char*>(input.CStr()), input.GetLength());
+ BIO *bio64 = BIO_new(BIO_f_base64());
+ BIO_push(bio64, biomem);
+ BIO_set_flags(bio64, BIO_FLAGS_BASE64_NO_NL);
+
+ auto *outbuf = new char[input.GetLength()];
+
+ size_t len = 0;
+ int rc;
+
+ while ((rc = BIO_read(bio64, outbuf + len, input.GetLength() - len)) > 0)
+ len += rc;
+
+ String ret = String(outbuf, outbuf + len);
+ BIO_free_all(bio64);
+ delete [] outbuf;
+
+ if (ret.IsEmpty() && !input.IsEmpty())
+ throw std::invalid_argument("Not a valid base64 string");
+
+ return ret;
+}