Base64 String Encoding and Decoding in C#

How to convert plain text string to base64 encoded string and vice versa in C#

Base64 is a radix-64 ASCII string format that represents binary data. Each digit of base64 encoded string represents exactly 6 bits of data.

It is designed to carry binary data across platforms that only support text content.

The usage is mostly popular in Web platform. For example it’s being used to embed image files inside HTML or embed font file inside CSS.

Even though the main purpose is to store binary data into a text content, base64 sometimes is being used to hide a text. For example to prevent the content of your website scraped by robot.

When I say to hide a text, that doesn’t mean it’s cryptographically secure. So you shouldn’t use it to store sensitive data like password or PIN.

String to Base64 Encoding C# Method

C# has built-in Base64 encoding method. But it only accepts binary data represented in array of bytes. To encode a plain text into a base64-encoded string, we need to convert it to array of bytes first. Then we can generate base64 encoded string from it.

public string Base64StringEncode(string originalString)
{
    var bytes = Encoding.UTF8.GetBytes(originalString);

    var encodedString = Convert.ToBase64String(bytes);

    return encodedString;
}

Base64 to String Decoding C# Method

C# also has built-in Base64 decoding method. But it only produces array of bytes. To get the original plain text from a base64-encoded string, we need to convert the array of bytes to string.

public string Base64StringDecode(string encodedString)
{
    var bytes = Convert.FromBase64String(encodedString);

    var decodedString = Encoding.UTF8.GetString(bytes);

    return decodedString;
}

Example

To use the base64 string encoding method, simply pass a plain text as parameter.

For base64 string decoding, simply pass a valid base64 string as parameter. Please note that if it isn’t a valid base64 string, it will throw an exception. So, better to wrap it in try catch.

var text = "The quick brown fox jumps over the lazy dog";
var encodedText = Base64StringEncode(string originalString);
var decodedText = Base64StringEncode(string originalString);

// Output:
//   encodedText => VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZw==
//   decodedText => The quick brown fox jumps over the lazy dog

That’s all I can write today. Thank you for reading!

References