| 66 | static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
| 67 | |
| 68 | size_t base64Encode(char const* data, size_t len, char* output, size_t outLen) { |
| 69 | if (outLen == 0) |
| 70 | return 0; |
| 71 | size_t written = 0; |
| 72 | |
| 73 | unsigned char ca3[3] = {0, 0, 0}; |
| 74 | unsigned char ca4[4] = {0, 0, 0, 0}; |
| 75 | const unsigned char* inPtr = (const unsigned char*)data; |
| 76 | int i = 0, j = 0, in_len = len; |
| 77 | |
| 78 | while (in_len--) { |
| 79 | ca3[i++] = *(inPtr++); |
| 80 | if (i == 3) { |
| 81 | ca4[0] = (ca3[0] & 0xfc) >> 2; |
| 82 | ca4[1] = ((ca3[0] & 0x03) << 4) + ((ca3[1] & 0xf0) >> 4); |
| 83 | ca4[2] = ((ca3[1] & 0x0f) << 2) + ((ca3[2] & 0xc0) >> 6); |
| 84 | ca4[3] = ca3[2] & 0x3f; |
| 85 | for (i = 0; (i < 4); i++) { |
| 86 | --outLen; |
| 87 | *output = base64_chars[ca4[i]]; |
| 88 | ++output; |
| 89 | ++written; |
| 90 | |
| 91 | if (outLen == 0) |
| 92 | return written; |
| 93 | } |
| 94 | i = 0; |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | if (i) { |
| 99 | for (j = i; j < 3; j++) |
| 100 | ca3[j] = '\0'; |
| 101 | ca4[0] = (ca3[0] & 0xfc) >> 2; |
| 102 | ca4[1] = ((ca3[0] & 0x03) << 4) + ((ca3[1] & 0xf0) >> 4); |
| 103 | ca4[2] = ((ca3[1] & 0x0f) << 2) + ((ca3[2] & 0xc0) >> 6); |
| 104 | ca4[3] = ca3[2] & 0x3f; |
| 105 | for (j = 0; (j < i + 1); j++) { |
| 106 | --outLen; |
| 107 | *output = base64_chars[ca4[j]]; |
| 108 | ++output; |
| 109 | ++written; |
| 110 | |
| 111 | if (outLen == 0) |
| 112 | return written; |
| 113 | } |
| 114 | while ((i++ < 3)) { |
| 115 | --outLen; |
| 116 | *output = '='; |
| 117 | ++output; |
| 118 | ++written; |
| 119 | |
| 120 | if (outLen == 0) |
| 121 | return written; |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | return written; |