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.

About these ads

37 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.

    • Const Says:

      @Alex: Actually base64 does not produce any non-ASCII characters. UTF-8 is not a magic trick to cover for “non-ASCII stuff”; there are other ASCII-compatible encodings out there, and if the _reader_ expects one of those, the “non-ASCII stuff” will appear as random characters.

  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.

  14. Spacemoses Says:

    Short, descriptive, informative, and to-the-point. I like code examples that don’t throw in tons of extra stuff like error checking and whatnot. Any savvy developer will know to add this in to their own implementation where needed. Thanks!

  15. jeet Says:

    Hi Arcane

    thank you for the post,
    well I have different sort of scenario.

    I have one big string on which I apply compression. then I apply Base64encoding, but sadly it increases size of the string ( compression :( ), what should I do? I use Zlib for the compression.

    pleas suggest
    jeet

    P.S. do you have idea about iphone programming?

  16. Sorgulama Says:

    Great thanks. What about just using,
    HttpUtility.UrlPathEncode(url)

  17. vaishali Says:

    Really nice and informative.

  18. Rajin Enosis Says:

    Thanx a lot. It was very much helpful!

  19. sehe Says:

    @Sorgulama: nobody was talking about URLs, just you.

  20. Fede Says:

    Really helpfull, i had a little change, to support accents, changed ASCIIEncoding, to UTF8Encoding.

  21. Ismael Miguel Says:

    private string encode(string text)
    {
    return System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(text));
    }

    this is the shortest way to encode…
    it’s the same but WAY much small and WAY much optimized…
    question: why optimized???
    answer: because i’m saving 2 huge vars (one array of strings and one string) and there is only one step with 5 instructions… the original has 3 steps with 7 instructions…

    private string decode(string text)
    {
    return System.Text.ASCIIEncoding.ASCII.GetString(System.Convert.FromBase64String(text));
    }

    this is how looks like the “compressed” function…

    jeet, base64 is not for compressing but for encoding…
    base64 increases the string size by 50%…
    (or something like that)…
    if i where you, i would firstlly encode, then compress…
    zip compression is based in dictionary, so, as many times a “group” of bytes is repeated, the smaller the size…
    try it…

    • Unbr0ken Says:

      Wouldn’t it be better to make the two tasks in the same function that allow it to choose what to do?

      Here’s a very compressed snippet:

      public static string EDCode(string Text, bool Encode)
      {
      return (Encode) ? Convert.ToBase64String(ASCIIEncoding.UTF8.GetBytes(Text)) : ASCIIEncoding.UTF8.GetString(Convert.FromBase64String(Text)); //It returns the string deciphered or ciphered, depending on the value of variable “X.”
      }

      Regards.

    • Unbr0ken Says:

      I have amended the code, i think it is better to use UTF8Encoding.

      private static string EDCode(string Text, bool Encode)
      {
      return (Encode) ? Convert.ToBase64String(UTF8Encoding.Unicode.GetBytes(Text)) : UTF8Encoding.Unicode.GetString(Convert.FromBase64String(Text));
      }

      Regards.

  22. Ismael Miguel Says:

    to reduce even more, there is one thing to do: add 2 lines

    under “Using System;”, add this:
    Using Convert;
    Using UTF8Encoding.Unicode;
    (…)

    the function will look like this:

    (…)
    private static string EDCode(string Text, bool Encode)
    {
    return (Encode) ? ToBase64String(GetBytes(Text)) : GetString(FromBase64String(Text));
    }
    (…)

    i hope it works…

    • Unbr0ken Says:

      “Same shit, different smell.”

      Dude, no offense, but… the fact of add “uses” don’t make it more compressed.

      However, it is a valid code, but with unnecessarily “uses” added.

  23. Ismael Miguel Says:

    lets see…
    acording to http://www.charcounter.com/ the version with useless uses have 187 chars…
    this was the “given” text:
    Using Convert;
    Using UTF8Encoding.Unicode;
    private static string EDCode(string Text, bool Encode)
    {
    return (Encode) ? ToBase64String(GetBytes(Text)) : GetString(FromBase64String(Text));
    }

    without those uses, the size is 202 chars…
    the text used was this:
    private static string EDCode(string Text, bool Encode)
    {
    return (Encode) ? Convert.ToBase64String(UTF8Encoding.Unicode.GetBytes(Text)) : UTF8Encoding.Unicode.GetString(Convert.FromBase64String(Text));
    }

    so, is less size is not compression, what is compression then???

    check by yourself…
    but there is one thing that i agree with you: “same shit, diferent smell”
    “same work, less space”

    • Unbr0ken Says:

      Dude… the fact of add uses at the top of code, or use it just when is needed, don’t make the code more compressed.

      At the final, if you debug the software, you can see that the program do the same callings to the .NET Classes, so… wherever you put the class names, the code will do the same thing, with the same size.

      Don’t matter if have or not more chars, the callings will be the same, and that is what really matter when the program is compiled.

      • Unbr0ken Says:

        By the way… the uses:

        Using Convert;
        Using UTF8Encoding.Unicode;

        Are internal clases and functions of “System.Text” and “System”, By this, it cannot be declared from “using”, what means that the code will not work.

  24. Ismael Miguel Says:

    dudes, im writting this by memory…
    im on my android…
    by the way, the final program compiled can have the same size with or without uses, but the size of the file with the code will change…
    but you all may be right:
    we usually use 4kb as the default size of atribution unit…
    so, those codes will result in 4kb of space on disk…
    am i wrong???

  25. Charles Kincaid Says:

    Amazing how many folks still confuse the amount of source code with the amount of code actually run by the computer.

    Arcane – It’s still a great post. Thanks

  26. decaptcher Says:

    hello!,I really like your writing so so much! share we communicate extra approximately your post on AOL? I require an expert on this area to unravel my problem. Maybe that is you! Having a look ahead to look you.

  27. bodo83 Says:

    Please don´t use ASCII if you are using special characters as Ü,Ö,Ä because “Glück” for example becomes “Gl?ck”. So better choose the following UTF8:

    String baseS = System.Convert.ToBase64String(System.Text.ASCIIEncoding.UTF8.GetBytes(“Glück”));
    String back = System.Text.ASCIIEncoding.UTF8.GetString(System.Convert.FromBase64String(baseS));

  28. A Fan Says:

    Thanks a bunch for this snippet! That saved me a lot of time :)

  29. GHD Says:

    Do you mind if I quote a few of your posts as long as I provide credit and sources back to your site?
    My blog site is in the very same niche as yours and my
    visitors would certainly benefit from some of the information you present here.

    Please let me know if this okay with you. Regards!

  30. one shot foaming automatic hand soap dispenser Says:

    Because the admin of this website is working, no question very rapidly
    it will be famous, due to its feature contents.


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 106 other followers

%d bloggers like this: