How do I encode and decode a base64 string?

  • How do I return a base64 encoded string given a string?

  • How do I decode a base64 encoded string into a string?


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

    I'm sharing my implementation with some neat features:

  • uses Extension Methods for Encoding class. Rationale is that someone may need to support different types of encodings (not only UTF8).
  • Another improvement is failing gracefully with null result 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 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);
            }
        }
    }
    

    andrew.fox答案略有差异,因为要解码的字符串可能不是正确的base64编码字符串:

    using System;
    
    namespace Service.Support
    {
        public static class Base64
        {
            public static string ToBase64(this System.Text.Encoding encoding, string text)
            {
                if (text == null)
                {
                    return null;
                }
    
                byte[] textAsBytes = encoding.GetBytes(text);
                return Convert.ToBase64String(textAsBytes);
            }
    
            public static bool TryParseBase64(this System.Text.Encoding encoding, string encodedText, out string decodedText)
            {
                if (encodedText == null)
                {
                    decodedText = null;
                    return false;
                }
    
                try
                {
                    byte[] textAsBytes = Convert.FromBase64String(encodedText);
                    decodedText = encoding.GetString(textAsBytes);
                    return true;
                }
                catch (Exception)
                {
                    decodedText = null;
                    return false;   
                }
            }
        }
    }
    
    链接地址: http://www.djcxy.com/p/22142.html

    上一篇: 如何在Node.js中提取POST数据?

    下一篇: 如何编码和解码base64字符串?