roo_io
API Documentation for roo_io
Loading...
Searching...
No Matches
base64.cpp
Go to the documentation of this file.
1#include "./arduino_base64.h"
2
3namespace {
4 constexpr char CODE[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
5
6 uint8_t indexOf(char search) {
7 for(uint8_t i = 0; i < 64; i++) {
8 if(::CODE[i] == search) {
9 return i;
10 }
11 }
12
13 return 0xFF;
14 }
15
16 void to6x4(uint8_t* input, uint8_t* output) {
17 output[0] = (input[0] & 0xFC) >> 2;
18 output[1] = ((input[0] & 0x03) << 4) + ((input[1] & 0xF0) >> 4);
19 output[2] = ((input[1] & 0x0F) << 2) + ((input[2] & 0xC0) >> 6);
20 output[3] = input[2] & 0x3F;
21 }
22
23 void to8x3(uint8_t* input, uint8_t* output) {
24 output[0] = (input[0] << 2) + ((input[1] & 0x30) >> 4);
25 output[1] = ((input[1] & 0x0F) << 4) + ((input[2] & 0x3C) >> 2);
26 output[2] = ((input[2] & 0x03) << 6) + input[3];
27 }
28}
29
30void base64::encode(const uint8_t* input, size_t inputLength, char* output) {
31 uint8_t position = 0;
32 uint8_t bit8x3[3] = {};
33 uint8_t bit6x4[4] = {};
34
35 while(inputLength--) {
36 bit8x3[position++] = *input++;
37
38 if(position == 3) {
39 ::to6x4(bit8x3, bit6x4);
40
41 for(const auto &v: bit6x4) {
42 *output++ = ::CODE[v];
43 }
44
45 position = 0;
46 }
47 }
48
49 if(position) {
50 for(uint8_t i = position; i < 3; i++) {
51 bit8x3[i] = 0x00;
52 }
53
54 ::to6x4(bit8x3, bit6x4);
55
56 for(uint8_t i = 0; i < position + 1; i++) {
57 *output++ = ::CODE[bit6x4[i]];
58 }
59
60 while(position++ < 3) {
61 *output++ = '=';
62 }
63 }
64
65 *output = '\0';
66}
67
68size_t base64::encodeLength(size_t inputLength) {
69 return (inputLength + 2 - ((inputLength + 2) % 3)) / 3 * 4 + 1;
70}
71
72void base64::decode(const char* input, size_t inputLength, uint8_t* output) {
73 uint8_t position = 0;
74 uint8_t bit8x3[3] = {};
75 uint8_t bit6x4[4] = {};
76
77 while(inputLength--) {
78 if(*input == '=') {
79 break;
80 }
81
82 bit6x4[position++] = ::indexOf(*input++);
83
84 if(position == 4) {
85 ::to8x3(bit6x4, bit8x3);
86
87 for(const auto &v: bit8x3) {
88 *output++ = v;
89 }
90
91 position = 0;
92 }
93 }
94
95 if(position) {
96 for(uint8_t i = position; i < 4; i++) {
97 bit6x4[i] = 0x00;
98 }
99
100 ::to8x3(bit6x4, bit8x3);
101
102 for(uint8_t i = 0; i < position - 1; i++) {
103 *output++ = bit8x3[i];
104 }
105 }
106}
107
108size_t base64::decodeLength(const char* input) {
109 auto inputLength = strlen(input);
110 uint8_t equal = 0;
111
112 input += inputLength - 1;
113
114 while(*input-- == '=') {
115 equal++;
116 }
117
118 return 6 * inputLength / 8 - equal;
119}
size_t decodeLength(const char *input)
Definition base64.cpp:108
void decode(const char *input, size_t inputLength, uint8_t *output)
Definition base64.cpp:72
void encode(const uint8_t *input, size_t inputLength, char *output)
Definition base64.cpp:30
size_t encodeLength(size_t inputLength)
Definition base64.cpp:68