http: utility: Add base64encode

Add the base64encode() function to be used to encode binary data
to offload out of the BMC. Based on crow/utility.h, reworked for
readability.

Tested: Added unit test cases. Also verified data encoded with this
        function was the same as the original binary when using
        a decoder.

Change-Id: I0a27ffb0090c4613e296af33d11e2e2657957167
Signed-off-by: Adriana Kobylak <anoo@us.ibm.com>
diff --git a/http/utility.hpp b/http/utility.hpp
index 5a184cc..0a61f3f 100644
--- a/http/utility.hpp
+++ b/http/utility.hpp
@@ -404,6 +404,64 @@
     using arg = typename std::tuple_element<i, std::tuple<Args...>>::type;
 };
 
+inline std::string base64encode(const std::string_view data)
+{
+    const std::array<char, 64> key = {
+        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
+        'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
+        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
+        'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
+        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
+
+    size_t size = data.size();
+    std::string ret;
+    ret.resize((size + 2) / 3 * 4);
+    auto it = ret.begin();
+
+    size_t i = 0;
+    while (i < size)
+    {
+        size_t keyIndex;
+
+        keyIndex = static_cast<size_t>(data[i] & 0xFC) >> 2;
+        *it++ = key[keyIndex];
+
+        if (i + 1 < size)
+        {
+            keyIndex = static_cast<size_t>(data[i] & 0x03) << 4;
+            keyIndex += static_cast<size_t>(data[i + 1] & 0xF0) >> 4;
+            *it++ = key[keyIndex];
+
+            if (i + 2 < size)
+            {
+                keyIndex = static_cast<size_t>(data[i + 1] & 0x0F) << 2;
+                keyIndex += static_cast<size_t>(data[i + 2] & 0xC0) >> 6;
+                *it++ = key[keyIndex];
+
+                keyIndex = static_cast<size_t>(data[i + 2] & 0x3F);
+                *it++ = key[keyIndex];
+            }
+            else
+            {
+                keyIndex = static_cast<size_t>(data[i + 1] & 0x0F) << 2;
+                *it++ = key[keyIndex];
+                *it++ = '=';
+            }
+        }
+        else
+        {
+            keyIndex = static_cast<size_t>(data[i] & 0x03) << 4;
+            *it++ = key[keyIndex];
+            *it++ = '=';
+            *it++ = '=';
+        }
+
+        i += 3;
+    }
+
+    return ret;
+}
+
 // TODO this is temporary and should be deleted once base64 is refactored out of
 // crow
 inline bool base64Decode(const std::string_view input, std::string& output)