43 static std::string encode(
const u_int8_t *cursor, int32_t size) {
44 char encodeLookup[] = BASE64_ENCODE_LOOKUP;
45 char padCharacter = BASE64_PAD_CHARACTER;
46 std::string encodedString;
47 encodedString.reserve(((size / 3) + (size % 3 > 0)) * 4);
50 for (int32_t idx = 0; idx < size / 3; idx++) {
51 temp = (*cursor++) << 16;
52 temp += (*cursor++) << 8;
54 encodedString.append(1, encodeLookup[(temp & 0x00FC0000) >> 18]);
55 encodedString.append(1, encodeLookup[(temp & 0x0003F000) >> 12]);
56 encodedString.append(1, encodeLookup[(temp & 0x00000FC0) >> 6]);
57 encodedString.append(1, encodeLookup[(temp & 0x0000003F)]);
62 temp = (*cursor++) << 16;
63 encodedString.append(1, encodeLookup[(temp & 0x00FC0000) >> 18]);
64 encodedString.append(1, encodeLookup[(temp & 0x0003F000) >> 12]);
65 encodedString.append(2, padCharacter);
68 temp = (*cursor++) << 16;
69 temp += (*cursor++) << 8;
70 encodedString.append(1, encodeLookup[(temp & 0x00FC0000) >> 18]);
71 encodedString.append(1, encodeLookup[(temp & 0x0003F000) >> 12]);
72 encodedString.append(1, encodeLookup[(temp & 0x00000FC0) >> 6]);
73 encodedString.append(1, padCharacter);
79 static std::vector <u_int8_t> decode(
const std::string &input) {
80 char padCharacter = BASE64_PAD_CHARACTER;
83 throw std::runtime_error(
"Non-Valid base64!");
87 if (input[input.size() - 1] == padCharacter)
89 if (input[input.size() - 2] == padCharacter)
93 std::vector <u_int8_t> decodedBytes;
94 decodedBytes.reserve(((input.size() / 4) * 3) - padding);
98 std::string::const_iterator cursor = input.begin();
99 while (cursor < input.end()) {
100 for (
size_t quantumPosition = 0; quantumPosition < 4; quantumPosition++) {
102 if (*cursor >= 0x41 && *cursor <= 0x5A)
103 temp |= *cursor - 0x41;
104 else if (*cursor >= 0x61 && *cursor <= 0x7A)
105 temp |= *cursor - 0x47;
106 else if (*cursor >= 0x30 && *cursor <= 0x39)
107 temp |= *cursor + 0x04;
108 else if (*cursor == 0x2B)
110 else if (*cursor == 0x2F)
112 else if (*cursor == padCharacter)
114 switch (input.end() - cursor) {
116 decodedBytes.push_back((temp >> 16) & 0x000000FF);
117 decodedBytes.push_back((temp >> 8) & 0x000000FF);
120 decodedBytes.push_back((temp >> 10) & 0x000000FF);
123 throw std::runtime_error(
"Invalid Padding in Base 64!");
126 throw std::runtime_error(
"Non-Valid Character in Base 64!");
130 decodedBytes.push_back((temp >> 16) & 0x000000FF);
131 decodedBytes.push_back((temp >> 8) & 0x000000FF);
132 decodedBytes.push_back((temp) & 0x000000FF);