How do I return a base64 encoded string given a string?
How do I decode a base64 encoded string into a string?
I'm sharing my implementation with some neat features:
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);
}
}
}
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!
public static string Base64Encode(string plainText) {
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
public static string Base64Decode(string base64EncodedData) {
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
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));