| 72 | } |
| 73 | |
| 74 | size_t Base64Encode(const uint8_t *in, size_t in_len, uint8_t *out) |
| 75 | { |
| 76 | static const char base64chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
| 77 | size_t resultIndex = 0; |
| 78 | |
| 79 | // increment over the length of the string, three characters at a time |
| 80 | for (size_t x = 0; x < in_len; x += 3) |
| 81 | { |
| 82 | // these three 8-bit (ASCII) characters become one 24-bit number |
| 83 | uint32_t n = in[x] << 16; |
| 84 | |
| 85 | if ((x + 2) < in_len) |
| 86 | { |
| 87 | n += (in[x + 1] << 8) + in[x + 2]; |
| 88 | } |
| 89 | else if ((x + 1) < in_len) |
| 90 | { |
| 91 | n += in[x + 1] << 8; |
| 92 | } |
| 93 | |
| 94 | // if we have one byte available, then its encoding is spread out over two characters |
| 95 | out[resultIndex++] = base64chars[(n >> 18) & 63]; |
| 96 | out[resultIndex++] = base64chars[(n >> 12) & 63]; |
| 97 | |
| 98 | if ((x + 2) < in_len) |
| 99 | { |
| 100 | out[resultIndex++] = base64chars[(n >> 6) & 63]; |
| 101 | out[resultIndex++] = base64chars[n & 63]; |
| 102 | } |
| 103 | else |
| 104 | { |
| 105 | if ((x + 1) < in_len) |
| 106 | { |
| 107 | out[resultIndex++] = base64chars[(n >> 6) & 63]; |
| 108 | } |
| 109 | else |
| 110 | { |
| 111 | out[resultIndex++] = '='; |
| 112 | } |
| 113 | out[resultIndex++] = '='; |
| 114 | } |
| 115 | |
| 116 | } |
| 117 | return resultIndex; |
| 118 | } |
| 119 | |
| 120 | } // namespace |
| 121 | |