Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How do I encode and decode a base64 string?

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

2. How would I decode a base64 encoded string into a string?
by

3 Answers

rahul07
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);
}
pankajshivnani123
Encode:
string encodedStr = Convert.ToBase64String(Encoding.UTF8.GetBytes("inputStr"));

Decode:
string inputStr = Encoding.UTF8.GetString(Convert.FromBase64String(encodedStr));
sandhya6gczb
uses Extension Methods for Encoding class. The rationale is that someone may need to support different types of encodings (not only UTF8).
Another improvement is failing gracefully with the null results 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 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);
}
}
}

Login / Signup to Answer the Question.