Base64 decode string to byte array

I feel like I have exhausted every resource online trying to find a routine to decode a Base64 encoded String. I need a method I can pass a String to and have it return something like an unsiged char[] or other form of byte array. Does anyone have anything?

1 Like

What about this 10 second Google search?

http://www.adp-gmbh.ch/cpp/common/base64.html

1 Like

Hi @ScruffR,

That decode method returns a string. I need to return an unsigned char array so I can get null bytes. That was the problem.

Here is my new working code:

void aes_client::base64_decode(const char *data, size_t input_length, size_t *output_length, unsigned char* outputData) {

    if (decoding_table == NULL) build_decoding_table();

    if (input_length % 4 != 0) return;

    int inputLength = input_length / 4 * 3;

//    *output_length = input_length / 4 * 3;
    if (data[input_length - 1] == '=') (inputLength)--;
    if (data[input_length - 2] == '=') (inputLength)--;

    unsigned char t[(size_t)inputLength];
//    unsigned char *decoded_data = t;
//    if (decoded_data == NULL) return;

    for (int i = 0, j = 0; i < input_length;) {

        uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];

        uint32_t triple = (sextet_a << 3 * 6)
        + (sextet_b << 2 * 6)
        + (sextet_c << 1 * 6)
        + (sextet_d << 0 * 6);

        if (j < inputLength) t[j++] = (triple >> 2 * 8) & 0xFF;
        if (j < inputLength) t[j++] = (triple >> 1 * 8) & 0xFF;
        if (j < inputLength) t[j++] = (triple >> 0 * 8) & 0xFF;
    }

    memcpy(outputData, t, inputLength);
}
1 Like