Cryptography Reference
In-Depth Information
( ( input[ 1 ] & 0x0F ) << 2 ) | ( ( input[ 2 ] & 0xC0 ) >> 6 ) ];
*output++ = base64[ ( input[ 2 ] & 0x3F ) ];
input += 3;
}
while ( len -= 3 );
*output = '\0';
}
Here, the output array is already assumed to have been allocated as 4/3 *
len . The input masks select 6 bits of the input at a time and process the input
in 3-byte chunks.
Base64 decoding is just as easy. Almost. Each input byte corresponds back
to six possible output bits. This mapping is the exact inverse of the encoding
mapping. However, when decoding, you have to be aware of the possibility that
you can receive invalid data. Remember that the input is given in 8-bit bytes, but
not every possible 8-bit combination is a legitimate Base64 character — this is,
in fact, the point of Base64. You must also reject non-aligned input here; if the
input is not a multiple of four, it didn't come from a conformant Base64 encod-
ing routine. For these reasons, there's a bit more error-checking that you need
to build into a Base64 decoding routine; when encoding, you can safely accept
anything, but when decoding, you must ensure that the input actually came
from a real Base64 encoder. Such a Base64 decoder is shown in Listing 1-15.
Listing 1-15: “base64.c” base64_decode
static int unbase64[] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52,
53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1
};
int base64_decode( const unsigned char *input, int len, unsigned char *output )
{
int out_len = 0, i;
assert( !( len & 0x03 ) ); // Is an even multiple of 4
do
{
for ( i = 0; i <= 3; i++ )
{
// Check for illegal base64 characters
if ( input[ i ] > 128 || unbase64[ input[ i ] ] == -1 )
(Continued)
 
Search WWH ::




Custom Search