| 30 | } |
| 31 | |
| 32 | char* base64_encode(const unsigned char* data, |
| 33 | size_t input_length, |
| 34 | size_t* output_length) { |
| 35 | |
| 36 | *output_length = 4 * ((input_length + 2) / 3); |
| 37 | |
| 38 | char* encoded_data = (char*)malloc(*output_length); |
| 39 | if (encoded_data == NULL) return NULL; |
| 40 | |
| 41 | for (int i = 0, j = 0; i < input_length;) { |
| 42 | |
| 43 | uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0; |
| 44 | uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0; |
| 45 | uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0; |
| 46 | |
| 47 | uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c; |
| 48 | |
| 49 | encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F]; |
| 50 | encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F]; |
| 51 | encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F]; |
| 52 | encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F]; |
| 53 | } |
| 54 | |
| 55 | for (int i = 0; i < mod_table[input_length % 3]; i++) |
| 56 | encoded_data[*output_length - 1 - i] = '='; |
| 57 | |
| 58 | return encoded_data; |
| 59 | } |
| 60 | |
| 61 | |
| 62 | unsigned char* base64_decode(const char* data, |