By Kevin Driedger


2012-07-31 15:06:24 8 Comments

  1. How do I return a base64 encoded string given a string?

  2. How do I decode a base64 encoded string into a string?

10 comments

@Zeigeist 2020-08-03 23:13:15

One liner code:

Note: Use System and System.Text directives.

Encode:

string encodedStr = Convert.ToBase64String(Encoding.UTF8.GetBytes("inputStr"));

Decode:

string inputStr = Encoding.UTF8.GetString(Convert.FromBase64String(encodedStr));

@juliushuck 2020-03-18 11:27:54

URL safe Base64 Encoding/Decoding

public static class Base64Url
{
    public static string Encode(string text)
    {
        return Convert.ToBase64String(Encoding.UTF8.GetBytes(text)).TrimEnd('=').Replace('+', '-')
            .Replace('/', '_');
    }

    public static string Decode(string text)
    {
        text = text.Replace('_', '/').Replace('-', '+');
        switch (text.Length % 4)
        {
            case 2:
                text += "==";
                break;
            case 3:
                text += "=";
                break;
        }
        return Encoding.UTF8.GetString(Convert.FromBase64String(text));
    }
}

@Momoro 2020-03-24 23:55:45

No problem, it's still interesting to see how to encode / decode a URL :)

@chetan chaphekar 2019-07-31 14:40:50

You can use below routine to convert string to base64 format

public static string ToBase64(string s)
{
    byte[] buffer = System.Text.Encoding.Unicode.GetBytes(s);
    return System.Convert.ToBase64String(buffer);
}

Also you can use very good online tool OnlineUtility.in to encode string in base64 format

@Momoro 2019-10-29 03:19:28

Online tools don't help in this situation -- He's asking how to CODE IT. I often wonder why people say "Check out this online tool!", because the OP didn't ask for an online tool :D

@Momoro 2019-09-22 04:02:06

You can display it like this:

var strOriginal = richTextBox1.Text;

byte[] byt = System.Text.Encoding.ASCII.GetBytes(strOriginal);

// convert the byte array to a Base64 string
string strModified = Convert.ToBase64String(byt);

richTextBox1.Text = "" + strModified;

Now, converting it back.

var base64EncodedBytes = System.Convert.FromBase64String(richTextBox1.Text);

richTextBox1.Text = "" + System.Text.Encoding.ASCII.GetString(base64EncodedBytes);
MessageBox.Show("Done Converting! (ASCII from base64)");

I hope this helps!

@Qwertie 2019-06-22 00:19:44

For those that simply want to encode/decode individual base64 digits:

public static int DecodeBase64Digit(char digit, string digit62 = "+-.~", string digit63 = "/_,")
{
    if (digit >= 'A' && digit <= 'Z') return digit - 'A';
    if (digit >= 'a' && digit <= 'z') return digit + (26 - 'a');
    if (digit >= '0' && digit <= '9') return digit + (52 - '0');
    if (digit62.IndexOf(digit) > -1)  return 62;
    if (digit63.IndexOf(digit) > -1)  return 63;
    return -1;
}

public static char EncodeBase64Digit(int digit, char digit62 = '+', char digit63 = '/')
{
    digit &= 63;
    if (digit < 52)
        return (char)(digit < 26 ? digit + 'A' : digit + ('a' - 26));
    else if (digit < 62)
        return (char)(digit + ('0' - 52));
    else
        return digit == 62 ? digit62 : digit63;
}

There are various versions of Base64 that disagree about what to use for digits 62 and 63, so DecodeBase64Digit can tolerate several of these.

@Sameera R. 2019-05-29 05:01:22

    using System;
    using System.Text;

    public static class Base64Conversions
    {
        public static string EncodeBase64(this string text, Encoding encoding = null)
        { 
            if (text == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = encoding.GetBytes(text);
            return Convert.ToBase64String(bytes);
        }

        public static string DecodeBase64(this string encodedText, Encoding encoding = null)
        {
            if (encodedText == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = Convert.FromBase64String(encodedText);
            return encoding.GetString(bytes);
        }
    }

Usage

    var text = "Sample Text";
    var base64 = text.EncodeBase64();
    base64 = text.EncodeBase64(Encoding.UTF8); //or with Encoding

@j2associates 2018-03-06 13:25:45

Based on the answers by Andrew Fox and Cebe, I turned it around and made them string extensions instead of Base64String extensions.

public static class StringExtensions
{
    public static string ToBase64(this string text)
    {
        return ToBase64(text, Encoding.UTF8);
    }

    public static string ToBase64(this string text, Encoding encoding)
    {
        if (string.IsNullOrEmpty(text))
        {
            return text;
        }

        byte[] textAsBytes = encoding.GetBytes(text);
        return Convert.ToBase64String(textAsBytes);
    }

    public static bool TryParseBase64(this string text, out string decodedText)
    {
        return TryParseBase64(text, Encoding.UTF8, out decodedText);
    }

    public static bool TryParseBase64(this string text, Encoding encoding, out string decodedText)
    {
        if (string.IsNullOrEmpty(text))
        {
            decodedText = text;
            return false;
        }

        try
        {
            byte[] textAsBytes = Convert.FromBase64String(text);
            decodedText = encoding.GetString(textAsBytes);
            return true;
        }
        catch (Exception)
        {
            decodedText = null;
            return false;
        }
    }
}

@João Antunes 2019-09-19 09:19:56

I would add a ParseBase64(this string text, Encoding encoding, out string decodedText) (to populate the exception if needed, and call that on the TryParseBase64

@Kevin Driedger 2012-07-31 15:06:24

Encode

public static string Base64Encode(string plainText) {
  var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
  return System.Convert.ToBase64String(plainTextBytes);
}

Decode

public static string Base64Decode(string base64EncodedData) {
  var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
  return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

@Sverrir Sigmundarson 2014-03-29 23:05:50

Null checks for input strings in both functions and the solution is perfect :)

@T.J. Crowder 2014-12-30 12:38:56

@SverrirSigmundarson: That or make them extension methods.

@ken 2015-02-02 18:44:05

@SverrirSigmundarson - Why do a null check? He's not the one dereferencing the input string. Null checks should prevent NullReferenceException in your own code, not somebody else's.

@Clément 2015-07-08 07:11:29

Alternate suggestion: Contracts (Contract.Requires(plainText != null)) and your code is perfect :)

@tne 2015-08-19 08:57:34

@ken And somebody else will say "you should only expose errors in your own code, not somebody else's", invoking the principle of least surprise, spiced with "fail early" and "proper encapsulation". Sometimes this means wrapping errors of lower-level components, sometimes something else entirely. In this case, I'll agree that wrapping a deref error is definitely dubious (plus we're all slowly agreeing to the fact that null as a concept is a bit of a hack to begin with), but we can still see some effects otherwise: the parameter name given in the exception might not be correct if left unchecked.

@steveen zoleko 2015-12-09 17:26:17

return System.Text.Encoding.UTF8.GetString(base64EncodedBytes, 0, base64EncodedBytes.Length); for windows phone 8

@Tatyana 2016-11-25 11:21:04

Do you know equivalent of this in javascript?

@nothingisnecessary 2017-09-21 15:47:17

@Tatyana In javaScript use atob() (alpha-to-binary) for encoding and btoa() for decoding

@Jared 2018-04-19 17:26:06

@ken I think a healthy compromise is to return null if null is received and just have that documented

@user1263981 2018-09-15 19:35:45

why can't decoding be done in one line? i.e. Encoding.UTF8.GetString(Convert.FromBase64String(base64Encod‌​edData))

@NH. 2018-12-04 22:07:12

@nothingisnecessary (and Tatyana), there is a separate question for that: stackoverflow.com/q/246801/1739000

@Mladen B. 2019-03-12 11:14:32

What if the underlying implementation of System.Convert.FromBase64String has the way to encode the null string? Doing the null check in your own code would override the standard behavior, right? The point here is that, in this case, we don't really use (dereference) the given string parameter but we're rather just passing it to the underlying implementation, essentially wrapping some functionality, creating a convenience method. Does it make sense to check for nulls in such case?

@Rogala 2019-08-08 17:26:34

Reference this all the time :)

@user1451111 2020-04-29 21:59:01

@user1263981 because he posted it as answer and answers here are read by everyone, including beginner programmers who don't know what are the correct namespaces. And one liner would make it too long for them.

@Cebe 2016-04-13 08:05:15

A slight variation on andrew.fox answer, as the string to decode might not be a correct base64 encoded string:

using System;

namespace Service.Support
{
    public static class Base64
    {
        public static string ToBase64(this System.Text.Encoding encoding, string text)
        {
            if (text == null)
            {
                return null;
            }

            byte[] textAsBytes = encoding.GetBytes(text);
            return Convert.ToBase64String(textAsBytes);
        }

        public static bool TryParseBase64(this System.Text.Encoding encoding, string encodedText, out string decodedText)
        {
            if (encodedText == null)
            {
                decodedText = null;
                return false;
            }

            try
            {
                byte[] textAsBytes = Convert.FromBase64String(encodedText);
                decodedText = encoding.GetString(textAsBytes);
                return true;
            }
            catch (Exception)
            {
                decodedText = null;
                return false;   
            }
        }
    }
}

@andrew.fox 2016-03-17 20:46:33

I'm sharing my implementation with some neat features:

  • uses Extension Methods for Encoding class. Rationale is that someone may need to support different types of encodings (not only UTF8).
  • Another improvement is failing gracefully with null result for null entry - it's very useful in real life scenarios and supports equivalence for X=decode(encode(X)).

Remark: Remember that to use Extension Method you have to (!) import the namespace with using keyword (in this case using MyApplication.Helpers.Encoding).

Code:

namespace MyApplication.Helpers.Encoding
{
    public static class EncodingForBase64
    {
        public static string EncodeBase64(this System.Text.Encoding encoding, string text)
        {
            if (text == null)
            {
                return null;
            }

            byte[] textAsBytes = encoding.GetBytes(text);
            return System.Convert.ToBase64String(textAsBytes);
        }

        public static string DecodeBase64(this System.Text.Encoding encoding, string encodedText)
        {
            if (encodedText == null)
            {
                return null;
            }

            byte[] textAsBytes = System.Convert.FromBase64String(encodedText);
            return encoding.GetString(textAsBytes);
        }
    }
}

Usage example:

using MyApplication.Helpers.Encoding; // !!!

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Test1();
            Test2();
        }

        static void Test1()
        {
            string textEncoded = System.Text.Encoding.UTF8.EncodeBase64("test1...");
            System.Diagnostics.Debug.Assert(textEncoded == "dGVzdDEuLi4=");

            string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);
            System.Diagnostics.Debug.Assert(textDecoded == "test1...");
        }

        static void Test2()
        {
            string textEncoded = System.Text.Encoding.UTF8.EncodeBase64(null);
            System.Diagnostics.Debug.Assert(textEncoded == null);

            string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);
            System.Diagnostics.Debug.Assert(textDecoded == null);
        }
    }
}

@t3chb0t 2018-06-22 06:10:35

Returning null in case of null is a very inconsistent behaviour. No other .net API that works with strings does that.

@andrew.fox 2018-06-22 09:35:15

@t3chb0t feel free to adjust it to your needs. As the way it's presented here was adjusted to ours. This is not a public API ;)

@Mladen B. 2019-03-12 11:12:11

Don't you now have to send 2 variables to the other party in your communication (to whom you're sending base64 encoded data)? You need to send both the encoding used and the actual base64 data? Isn't it easier if you use a convention on both sides to use the same encoding? That way you'd only have to send base64 data, right?

Related Questions

Sponsored Content

40 Answered Questions

63 Answered Questions

[SOLVED] What is the difference between String and string in C#?

12 Answered Questions

[SOLVED] Creating a BLOB from a Base64 string in JavaScript

  • 2013-04-26 21:51:20
  • Jeremy
  • 482193 View
  • 461 Score
  • 12 Answer
  • Tags:   javascript base64

26 Answered Questions

[SOLVED] How can you encode a string to Base64 in JavaScript?

13 Answered Questions

[SOLVED] Base64 encoding and decoding in client-side Javascript

  • 2010-05-12 15:25:00
  • Mo.
  • 666589 View
  • 274 Score
  • 13 Answer
  • Tags:   javascript base64

7 Answered Questions

[SOLVED] How to do Base64 encoding in node.js?

20 Answered Questions

[SOLVED] Decode Base64 data in Java

  • 2009-01-22 15:55:18
  • Ryan P
  • 745522 View
  • 485 Score
  • 20 Answer
  • Tags:   java base64

15 Answered Questions

[SOLVED] Binary Data in JSON String. Something better than Base64

  • 2009-09-18 08:08:05
  • dmeister
  • 498125 View
  • 626 Score
  • 15 Answer
  • Tags:   json base64

20 Answered Questions

[SOLVED] How to check whether a string is Base64 encoded or not

  • 2011-12-20 06:16:24
  • loganathan
  • 243333 View
  • 196 Score
  • 20 Answer
  • Tags:   base64

2 Answered Questions

[SOLVED] How do I decode a base64 encoded string?

  • 2011-08-20 21:34:51
  • Rickard
  • 326484 View
  • 262 Score
  • 2 Answer
  • Tags:   c# encoding base64

Sponsored Content