Skip to content

Commit de86718

Browse files
committed
Base64 implemented.
1 parent 96df9a8 commit de86718

File tree

3 files changed

+64
-1
lines changed

3 files changed

+64
-1
lines changed

lib/headers/base64url/container.hpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,13 @@
66
#include <regex>
77

88
namespace base64url {
9+
static const std::string chars =
10+
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
11+
"abcdefghijklmnopqrstuvwxyz"
12+
"0123456789-_";
13+
914
struct container {
15+
std::string static encode(const std::string & input, bool padding = true);
16+
std::string static decode(const std::string & input);
1017
};
1118
}

lib/sources/container.cpp

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,43 @@
11
#include <base64url/container.hpp>
22

33
namespace base64url {
4+
std::string container::encode(const std::string &input, bool padding) {
5+
std::string output;
6+
int value = 0;
7+
int value_b = -6;
8+
9+
for (const unsigned char character : input) {
10+
value = (value << 8) + character;
11+
value_b += 8;
12+
while (value_b >= 0) {
13+
output.push_back(chars[(value >> value_b) & 0x3F]);
14+
value_b -= 6;
15+
}
16+
}
17+
if (value_b > -6)
18+
output.push_back(chars[((value << 8) >> (value_b + 8)) & 0x3F]);
19+
20+
if (padding)
21+
while (output.size() % 4 != 0)
22+
output.push_back('=');
23+
24+
return output;
25+
}
26+
27+
std::string container::decode(const std::string &input) {
28+
std::string output;
29+
int value = 0;
30+
int value_b = -8;
31+
for (const char character : input) {
32+
if (character == '=') break;
33+
auto position = chars.find(character);
34+
value = (value << 6) + position;
35+
value_b += 6;
36+
if (value_b >= 0) {
37+
output.push_back(static_cast<char>((value >> value_b) & 0xFF));
38+
value_b -= 8;
39+
}
40+
}
41+
return output;
42+
}
443
}

tests/implementation_test.cc

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,23 @@
11
#include <gtest/gtest.h>
22
#include <base64url/container.hpp>
33

4-
TEST(Base64URL, Assertions) {
4+
TEST(Base64URL, Encode) {
55
using namespace base64url;
6+
const std::string input = "hello world";
7+
const std::string output = container::encode(input);
8+
ASSERT_EQ(output, "aGVsbG8gd29ybGQ=");
9+
10+
const std::string output_no_padding = container::encode(input, false);
11+
ASSERT_EQ(output_no_padding, "aGVsbG8gd29ybGQ");
12+
}
13+
14+
TEST(Base64URL, Decode) {
15+
using namespace base64url;
16+
const std::string input = "aGVsbG8gd29ybGQ=";
17+
const std::string output = container::decode(input);
18+
ASSERT_EQ(output, "hello world");
19+
20+
const std::string input_no_padding = "aGVsbG8gd29ybGQ";
21+
const std::string output_no_padding = container::decode(input_no_padding);
22+
ASSERT_EQ(output_no_padding, "hello world");
623
}

0 commit comments

Comments
 (0)