ptth/bare_minimum_crypto/cpp/string_helpers.cpp

63 lines
1.3 KiB
C++

#include "string_helpers.h"
#include <iostream>
#include "cpp-base64/base64.h"
namespace BareMinimumCrypto {
using namespace std;
vector <uint8_t> copy_to_bytes (const string & s) {
return vector <uint8_t> ((const uint8_t *)&s [0], (const uint8_t *)&s [s.size ()]);
}
string base64_encode (const vector <uint8_t> & v) {
return ::base64_encode (string_view ((const char *)v.data (), v.size ()));
}
optional <vector <uint8_t>> 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;
}
vector <uint8_t> 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;
}
}