Base64 is an encoding for transferring binary data in 7-bit text. Originally used in email, it is also used for binary encoding data in HTML files. Another common use for Base64 is in HTTP Basic Access Authentication where it is used to transfer login details (which might not be printable characters).
The key library for handling Base64 on the Mac is normally libcrypto (the OpenSSL library), so it's a little disappointing that libcrypto isn't available on the iPhone.
Using OpenSSL
Via the command line
On the Mac, you can handle simple encoding tasks like base64 encoding with OpenSSL on the command line:
echo "Base64 encode this text." | openssl enc -base64
gives the encoding result:
QmFzZTY0IGVuY29kZSB0aGlzIHRleHQuCg==
The reverse is handled in the following manner:
echo "QmFzZTY0IGVuY29kZSB0aGlzIHRleHQuCg==" | openssl enc -d -base64
giving
Base64 encode this text.
In code
As you'd expect, doing the same work in code takes a little more typing. First, we're using a library, so we need to include it (in your Project's Build Settings under Other Linker Flags add the flag -lcrypto). Once that's done, you should be able to use the following method in a category on NSData:
#include#include - (NSString *)base64EncodedString { // Construct an OpenSSL context BIO *context = BIO_new(BIO_s_mem()); // Tell the context to encode base64 BIO *command = BIO_new(BIO_f_base64()); context = BIO_push(command, context);