Friday, June 10, 2005

Base 64 Encoding/Decoding using .NET

Sometimes binary data needs to be represented in a text-friendly format. For instance, maybe you need to include the bits of an image file within an XML document. To do this, we typically use Base64 Encoding.

Back in the VB6 days, I had a couple of subroutines that did my encoding and decoding for me. Now, with the .NET Framework, it's extremely easy to do.

For instance, to encode a string into Base64, you simply do the following:

string b64=Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(s));

But wait! Didn't I say that Base64 was used to encode binary data? Well, yes, but a string can be transformed into binary data (a.k.a., a byte[] array), and that binary data is what is transformed.

There are different ways to represent a string as bytes of data (remember that not everyone uses the same Character Set as us-english, so some languages must use Unicode). In this example, I use the ASCII encoding class's GetBytes() method to generate the byte array for me from my string variable named "s". Each character in "s" will be represented by a single byte in my array.

Decoding a Base64 string is similarly easy:

string s=System.Text.Encoding.ASCII.GetString(Convert.FromBase64String(b64));

A little warning here: I had to guess that my Base64 data was ASCII encoded, so I used the GetString() method of the ASCII class to decode the byte array into a string. If you use the wrong text encoding class to decode the byte array, then you could get garbage data. If you control both ends of the conversion process, then this shouldn't be a problem, but you do need to be aware of what different encoding schemes are out there.

Here is the code for a console app that will decode Base64 strings for you. The assumption is that the byte array was ASCII encoded, as above. Run the application and type or paste your Base64 data into the console. Enter two blank lines at the end, and it will then display the decoded ASCII text.

Notice that if you want to use this as an encoder, then simply uncomment the encoding line and comment out the decoding line.

using System;

namespace scratch
class Class1
static void Main(string[] args)
string s="";

string y = Console.ReadLine();
while (y != "")
s += y + "\n";
if (y=="")
// Convert collected string to Base64
// Console.WriteLine(
// Convert.ToBase64String(
// System.Text.Encoding.ASCII.GetBytes(s)));

// Convert collected Base64 string to ASCII