openssl base64 decode function is not working for specfic string

I have the below openssl code to decode json content, it works fine if the encoded data is "eyJ0ZXN0MSI6eyJ2YWwyIjotOTEuNiwidmFsMyI6NDAuMTIzNH19" but it does not work if the encoded data is "eyJ0ZXN0MSI6eyJsYXRpdHVkZSI6LTkxLjYsInZhbDMiOjQwfX0". Its not decoding the last 2 right curly braces. Can somebody help me to understand why this is happening?

Note: the encoded string is the payload generated from jwt.io

1
2
3
4
5
6
7
8
9
10
11
12
vector<unsigned char> Base64Decode(const char* encoded)
{
    unique_ptr<BIO,BIOFreeAll> b64(BIO_new(BIO_f_base64()));
    BIO_set_flags(b64.get(), BIO_FLAGS_BASE64_NO_NL);
    BIO* source = BIO_new_mem_buf((void*)encoded, -1); // read-only source
    BIO_push(b64.get(), source);
    const int maxlen = (strlen(encoded) / 4 * 3 + 1)+2;
    vector<unsigned char> decoded(maxlen);
    const int len = BIO_read(b64.get(), decoded.data(), maxlen);
    decoded.resize(len);
    return decoded;
}
Last edited on
Your second encoded string is missing a character. Try adding '=' to the end.

And remember to:

[code]
put code between code tags to preserve indentation, etc.
[/code]
Last edited on
I don't have control over the encoded data, i get it from other party. Looks like its a valid encoded data because all online websites are decoding it properly
Those sites are obviously padding the string with '=' to make it a multiple of 4, since that's what base64 needs for proper decoding. You should do the same.
Looks like its a valid encoded data because all online websites are decoding it properly

echo eyJ0ZXN0MSI6eyJsYXRpdHVkZSI6LTkxLjYsInZhbDMiOjQwfX0 | base64 -d
{"test1":{"latitude":-91.6,"val3":40}}base64: invalid input

So, the 2nd is not valid base64. You should consider the advice given above,
Last edited on
padding the string with '=' to make it a multiple of 4


Just to clarify something. Base64 uses 3 bytes to encode 4 characters. So the encoded string (the input to your function) should have a length that is a multiple of 3. You should pad with '=' to make the string length a multiple of 3.

If no padding were required, the decoded string will have a length that is a multiple of 4. The decoded string will not be a multiple of 4 is padding is required.

Info: https://en.wikipedia.org/wiki/Base64
yes i will pad it with "=" before decoding, Thanks a lot for clarifying this.
Topic archived. No new replies allowed.