Encoding Strings to Base64 in C#

I recently had the need to convert simple strings back and forth from Base64 encoding. It turned out to be relatively simple in .Net, once you figured out which class libraries you needed to combine.

It turns out the System.Convert has two handy methods for dealing with Base64, ToBase64String and FromBase64String. On the ToBase64String, we have a bit of a challenge, since it expects a byte array and not a string to be passed in.

It does make a certain amount of sense, typically you aren’t encoding a simple string but instead a binary object such as a file, which is usually represented as an array of bytes. For us, this means we have to take our string and convert it to a byte array.

You’d think the string class would have a nice static method to handle this, but alas it does not. Instead we have to turn to System.Text. I imagine most of you are working with ASCII encoding, so here we’ll call on the ASCIIEncoding.ASCIII class, and use it’s GetBytes to convert a string to bytes.

The small method below combines the two methods I’ve described to create a Base64 encoded string from a normal string.

    static public string EncodeTo64(string toEncode)

    {

      byte[] toEncodeAsBytes

            = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);

      string returnValue

            = System.Convert.ToBase64String(toEncodeAsBytes);

      return returnValue;

    }

 

Note two things, first I am using ASCII encoding, which should cover most folks. Just in case though, System.Text has encodings for the various flavors of UTF as well as Unicode. Just choose the appropriate encoding method for your need.

Second, I made the class static because I was using a console app for my test harness. While it could be static in your class, there’s no reason it has to be. Your choice.

OK, we’ve got the string encoded, at some point we’re going to want to decode it. We essentially do the reverse of encoding, we call the FromBase64String and pass in our encoded string, which returns a byte array. We then call the AsciiEncoding GetString to convert our byte array to a string. Here’s a small method to Decode your Base64 strings.

    static public string DecodeFrom64(string encodedData)

    {

      byte[] encodedDataAsBytes

          = System.Convert.FromBase64String(encodedData);

      string returnValue =

         System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);

      return returnValue;

    }

 

Finally, here’s a simple test harness, done in a console app, to show you calls to the two methods.

 

      string myData = “Here is a string to encode.”;

 

      string myDataEncoded = EncodeTo64(myData);

      Console.WriteLine(myDataEncoded);

 

      string myDataUnencoded = DecodeFrom64(myDataEncoded);

      Console.WriteLine(myDataUnencoded);

 

      Console.ReadLine();

 

Be aware, I’ve done no error checking here. My little methods assume that the data you are decoding will properly convert to and from a string. If that’s not the case you could wind up with a serious case of gibberish, if not cause a run time exception. If you are not positive that all you are dealing with is simple strings, then make effort to include some try / catch logic in your implementation.

13 Responses to “Encoding Strings to Base64 in C#”

  1. Haroon Emmanuel Says:

    Hey mate ! how would i convert a string into 28 bytes and then
    EncodeTo64 which you have told already !

    Suppose i have a string

    haroon123 how will i convert to 28 bytes… i guess would use padding and stuff ..but not sure please help !

  2. arcanecode Says:

    Pretty simple:
    string message = “haroon123″;
    message.PadRight(28);

    And that’s it, your message will now be
    “haroon123 “.
    If you want the spaces in front, use the PadLeft method instead.

    –Arcane

  3. Haroon Emmanuel Says:

    Cheers Mate ! :)

  4. Sri Says:

    Hi
    i used your methods to store password to access database. they encrypt well but when i try to decrypt it dosen’t work. it wont give the original string. why is that?

  5. Abhishek Says:

    Grrrrrrrrrrrrrrrrrrrrr8 Code…..
    Hi Sri , I think u must b making some mestiq. it is working .
    /****************************************/
    StreamReader reader = new StreamReader(csvFileLocation);
    string encData = reader.ReadLine();

    string data = License.DecodeFrom64(encData.ToString());
    /****************************************/

    This is how i used this Code.
    Cheers…….

  6. dario Says:

    Hi, how can i use this as a stored procedure in sql server 2005?

    Any ideas…?

    Thanks in advance

  7. Encoding Strings to Base64 in C# « r.belter Says:

    [...] Source: Encoding Strings to Base64 in C# « Arcane Code [...]

  8. Gustavo Says:

    Thanks for the post. It was usefull for me.

    Gustavo

  9. Alex Says:

    You know, there’s never a need to use ASCII. As long as you’re using only characters from the ASCII character set, UTF-8 is identical to ASCII. Therefore, if you use UTF-8 instead, you’ll get the same result as when using ASCII, but you’re also covered if any non-ASCII stuff comes along.

  10. David Says:

    Great post. Just what I needed to know about to and from Base64String conversions.

    Alex is correct about UTF-8. But each of the UTF encodings are designed to natively support encoding a particular subset of characters, and to ‘fail gracefully’ when encoding anything outside that character set by escaping and mapping a multiple character combination to represent the not natively supported characters. Apparently with UTF-8 this can result in lots of escaping and has the potential for a single character modification (infidelity) to dramatically alter the interpretation of the remaining string – so it is a little more fragile with respect to the size of the loss in the event of minor corruption.

    By the way, the .NET string datatype stores content internally using UTF-16 encoding – so that’s probably a pretty safe bet for most cases – might want to use that as your default. Again, if an unsupported character comes along, it will be encoded and decoded using an escape sequence – it will just take more bytes to represent it when that occurs.

  11. Prakash Kumar Says:

    It’s really useful. thanks and keep going on

  12. Robin Says:

    Never use Base64 to store Passwds.
    Use it to save Binary Files in a ASCII Format. Eg an Image file in a XML Config.

    Thanks for this code. I didnt know how to do this in C# yet. ;)

  13. Karl Says:

    Thanks arcanecode. Your example is just what I needed.


Leave a Reply