Base64 encoding

This has come more than a few times too, that is what is Base64 encoding and how do you use it in .NET. Wikipedia defines Base64 encoding as:
"The term Base64 refers to a specific MIME content transfer encoding. It is also used as a generic term for any similar encoding scheme that encodes binary data by treating it numerically and translating it into a base 64 representation."
For the lay-developer, all you really need to know – is Base64 encoding is a way for you to represent data in a way that is guaranteed to be human-readable, and note that it does take up slightly more space than the original string. Why is this important? Well for encryption routines for examples. If you encrypt a string, it returns back an array of bytes. If you translate those into characters, many/most will not be readable. But worse, you will likely get an ASCII zero (0) at some point in the string. When you do, that’s consider an end of line by most. So if you treat the output of an encryption routine as a string, you will likely (or at least some of the time) truncate the value – making it unreadable and irreversible encrypted.
So you need to either keep the output as a byte array (which can be a pain, let’s be honest!) – or you can just dump it out as base64 encoded, which will turn it into a squence of numbers and letters (and a couple of special characters). Now you can work with the output in a standard string format – which means it can be stored in a text file or even written down onto paper!
Base64 encoding can be used for a lot of things, but this is probably one of the more common needs – and below is how you go about using it when you are dealing with ASCII:

string inputString = "The quick brown fox jumped over the lazy dog.";

byte[] bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(inputString);

// Encode
string base64String = Convert.ToBase64String(bytes);

// Decode
byte[] outBytes = Convert.FromBase64String(base64String);

string outputString = System.Text.ASCIIEncoding.ASCII.GetString(outBytes);

Posted in General, Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.


Enter your email address to follow this blog and receive notifications of new posts by email.

Join 9 other followers

%d bloggers like this: