#include "string_helpers.h" #include #include "cpp-base64/base64.h" namespace BareMinimumCrypto { using namespace std; Bytes copy_to_bytes (const string & s) { return Bytes ((const uint8_t *)&s [0], (const uint8_t *)&s [s.size ()]); } string base64_encode (const Bytes & v) { return ::base64_encode (string_view ((const char *)v.data (), v.size ())); } optional base64_decode (const string & s) { try { const auto decoded = ::base64_decode (s); return copy_to_bytes (decoded); } catch (const exception &) { return nullopt; } } int test_base64 () { // I assume that char is 8 bits // char is C++ nonsense inherited from C nonsense if (sizeof (char) != sizeof (uint8_t)) { cerr << "char is not the same size as uint8_t" << endl; return 1; } Bytes v {1, 2, 3, 4, 5, 6}; const auto s = base64_encode (v); if (s != "AQIDBAUG") { cerr << "Base64 encoding failed" << endl; return 1; } // Trivial decode const auto v2 = std::move (*base64_decode (s)); if (v2 != v) { cerr << "Base64 trivial decode failed" << endl; return 1; } // Decode should fail const auto v3 = base64_decode ("AQIDBAUG."); if (v3 != nullopt) { cerr << "Base64 decode should have failed" << endl; return 1; } return 0; } }