Base64::convertFromBase64 should be more forgiving

When converting a base64 from the payload of a JSON Web Token (aka JWT) I discovered that the base64 string was ‘slightly out of spec’ in that it was not padded to ensure it’s length was a multiple of 4. To solve this problem I had to append some padding characters to it for Base64::convertFromBase64 to work. Maybe this could happen internally? Here is what I ended up doing

payloadBase64 += String (std::string (payloadBase64.length() % 4, '='));

It’s not only JWT. It seems that every single base64 algorithm I have tried was omitting the padding.

Here is a good summary:

1 Like

Here is a base64_decode I found that always works:

	std::string base64_decode (const std::string &in)
		std::string out;

		std::vector<int> T (256, -1);
		for (int i = 0; i < 64; i++) T["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[i]] = i;

		int val = 0, valb = -8;
		for (unsigned char c : in)
			if (T[c] == -1) break;
			val = (val << 6) + T[c];
			valb += 6;
			if (valb >= 0)
				out.push_back (char ((val >> valb) & 0xFF));
				valb -= 8;
		return out;

Is there another problem this code solves? ie. is missing the padding not the only issue?

Not that I’m aware. I just had problems decoding base64 encoded strings from our server (using PHP 7.2 64-bit) and then found that algorithm online. I’ve used that as I couldn’t figure out right away why the base64_decode in JUCE wasn’t working.

Ahh… My one-liner should fix it. :slight_smile: