21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

*p = 0;<br />

return output;<br />

}<br />

}<br />

}<br />

The public interface to the above code is the following:<br />

unsigned char *spc base64_encode(unsigned char *input, size_t len, int wrap);<br />

The result is a NULL-terminated string allocated internally via malloc( ). Some protocols<br />

may expect you to “wrap” base64-encoded data so that, when printed, it takes<br />

up less than 80 columns. If such behavior is necessary, you can pass in a non-zero<br />

value for the final parameter, which will cause this code to insert newlines once every<br />

76 characters. In that case, the string will always end with a newline (followed by the<br />

expected NULL-terminator).<br />

If the call to malloc( ) fails because there is no memory, this function returns 0.<br />

See Also<br />

Recipe 4.6<br />

4.6 Performing Base64 Decoding<br />

<strong>Problem</strong><br />

You have a base64-encoded string that you’d like to decode.<br />

Solution<br />

Use the inverse of the algorithm for encoding, presented in Recipe 4.5. This is most<br />

easily done via table lookup, mapping each character in the input to six bits of output.<br />

Discussion<br />

Following is our code for decoding a base64-encoded string. We look at each byte<br />

separately, mapping it to its associated 6-bit value. If the byte is NULL, we know that<br />

we’ve reached the end of the string. If it represents a character not in the base64 set,<br />

we ignore it unless the strict argument is non-zero, in which case we return an<br />

error.<br />

The RFC that specifies this encoding says you should silently ignore<br />

any unnecessary characters in the input stream. If you don’t have to do<br />

so, we recommend you don’t, as this constitutes a covert channel in<br />

any protocol using this encoding.<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.<br />

Performing Base64 Decoding | 125

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!