How do I encode and decode a base64 string?

Kevin Driedger picture Kevin Driedger · Jul 31, 2012 · Viewed 884.8k times · Source
  1. How do I return a base64 encoded string given a string?

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

Answer

Kevin Driedger picture Kevin Driedger · Jul 31, 2012

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);
}