2021-01-17 21:36:56 +00:00
|
|
|
#include "string_helpers.h"
|
|
|
|
|
2021-01-17 21:58:35 +00:00
|
|
|
#include <iostream>
|
|
|
|
|
2021-01-17 21:36:56 +00:00
|
|
|
#include "cpp-base64/base64.h"
|
|
|
|
|
|
|
|
namespace BareMinimumCrypto {
|
|
|
|
using namespace std;
|
|
|
|
|
2021-01-20 01:31:41 +00:00
|
|
|
Bytes copy_to_bytes (const string & s) {
|
|
|
|
return Bytes ((const uint8_t *)&s [0], (const uint8_t *)&s [s.size ()]);
|
2021-01-17 21:36:56 +00:00
|
|
|
}
|
|
|
|
|
2021-01-20 01:31:41 +00:00
|
|
|
string base64_encode (const Bytes & v) {
|
2021-01-17 21:36:56 +00:00
|
|
|
return ::base64_encode (string_view ((const char *)v.data (), v.size ()));
|
|
|
|
}
|
|
|
|
|
2021-01-20 01:31:41 +00:00
|
|
|
optional <Bytes> base64_decode (const string & s) {
|
2021-01-17 21:36:56 +00:00
|
|
|
try {
|
2021-01-17 21:58:35 +00:00
|
|
|
const auto decoded = ::base64_decode (s);
|
2021-01-17 21:36:56 +00:00
|
|
|
return copy_to_bytes (decoded);
|
|
|
|
}
|
|
|
|
catch (const exception &) {
|
|
|
|
return nullopt;
|
|
|
|
}
|
|
|
|
}
|
2021-01-17 21:58:35 +00:00
|
|
|
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2021-01-20 01:31:41 +00:00
|
|
|
Bytes v {1, 2, 3, 4, 5, 6};
|
2021-01-17 21:58:35 +00:00
|
|
|
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;
|
|
|
|
}
|
2021-01-17 21:36:56 +00:00
|
|
|
}
|