Encode/Decode base64 Strings using C#.NET

When testing systems, it can be useful to see what’s hidden behind a base64 string. Maybe we are running a secuirty audit and come across an HTTP endpoint using Basic Authentication  :O and we want to illustrate to those that don’t understand the risk and why it should be changed (well, it looks encrypted to a non-technical person…). You might need this for any number of reasons. Maybe you just want to try it for knowledge’s sake. Lucky for us, .NET has wonderful built in methods for working with base64.

Here are the aforementioned methods:

// Decode
var data = Convert.FromBase64String(encodedString);
var decodedString = Encoding.UTF8.GetString(data);

// Encode
var data = Encoding.UTF8.GetBytes(plainText);
var encodedString = Convert.ToBase64String(data);

Or the more compact:

// Decode
var decodedString = Encoding.UTF8.GetString(Convert.FromBase64String(encodedString));

// Encode
var encodedString = Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText));

And there you have it. It is that simple! Throw that into a method of your own and drop it into your reusable class library for future use (with a nice fancy name like Base64.Encode() so you’ll always remember what it does).

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: