File tree Expand file tree Collapse file tree 3 files changed +64
-1
lines changed Expand file tree Collapse file tree 3 files changed +64
-1
lines changed Original file line number Diff line number Diff line change 6
6
#include < regex>
7
7
8
8
namespace base64url {
9
+ static const std::string chars =
10
+ " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
11
+ " abcdefghijklmnopqrstuvwxyz"
12
+ " 0123456789-_" ;
13
+
9
14
struct container {
15
+ std::string static encode (const std::string & input, bool padding = true );
16
+ std::string static decode (const std::string & input);
10
17
};
11
18
}
Original file line number Diff line number Diff line change 1
1
#include < base64url/container.hpp>
2
2
3
3
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
+ }
4
43
}
Original file line number Diff line number Diff line change 1
1
#include < gtest/gtest.h>
2
2
#include < base64url/container.hpp>
3
3
4
- TEST (Base64URL, Assertions ) {
4
+ TEST (Base64URL, Encode ) {
5
5
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" );
6
23
}
You can’t perform that action at this time.
0 commit comments