| 60 | |
| 61 | |
| 62 | unsigned char* base64_decode(const char* data, |
| 63 | size_t input_length, |
| 64 | size_t* output_length) { |
| 65 | |
| 66 | if (decoding_table == NULL) build_decoding_table(); |
| 67 | |
| 68 | if (input_length % 4 != 0) return NULL; |
| 69 | |
| 70 | *output_length = input_length / 4 * 3; |
| 71 | if (data[input_length - 1] == '=') (*output_length)--; |
| 72 | if (data[input_length - 2] == '=') (*output_length)--; |
| 73 | |
| 74 | unsigned char* decoded_data = (unsigned char*)malloc(*output_length); |
| 75 | if (decoded_data == NULL) return NULL; |
| 76 | |
| 77 | for (int i = 0, j = 0; i < input_length;) { |
| 78 | |
| 79 | uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]]; |
| 80 | uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]]; |
| 81 | uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]]; |
| 82 | uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]]; |
| 83 | |
| 84 | uint32_t triple = (sextet_a << 3 * 6) |
| 85 | + (sextet_b << 2 * 6) |
| 86 | + (sextet_c << 1 * 6) |
| 87 | + (sextet_d << 0 * 6); |
| 88 | |
| 89 | if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF; |
| 90 | if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF; |
| 91 | if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF; |
| 92 | } |
| 93 | |
| 94 | return decoded_data; |
| 95 | } |
no test coverage detected