4.6. Performing Base64 Decoding
Problem
You have a base64-encoded string that you’d like to decode.
Solution
Use the inverse of the algorithm for encoding, presented in Recipe 4.5. This is most easily done via table lookup, mapping each character in the input to six bits of output.
Discussion
Following is our code for decoding a base64-encoded string. We look
at each byte separately, mapping it to its associated 6-bit value. If
the byte is NULL, we know that
we’ve reached the end of the string. If it
represents a character not in the base64 set, we ignore it unless the
strict argument is non-zero, in which case we
return an error.
Warning
The RFC that specifies this encoding says you should silently ignore any unnecessary characters in the input stream. If you don’t have to do so, we recommend you don’t, as this constitutes a covert channel in any protocol using this encoding.
Note that we check to ensure strings are properly padded. If the string isn’t properly padded or otherwise terminates prematurely, we return an error.
#include <stdlib.h> #include <string.h> static char b64revtb[256] = { -3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*0-15*/ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*16-31*/ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /*32-47*/ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, /*48-63*/ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /*64-79*/ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access