How do I encode and decode a base64 string?

前端 未结 10 2438
我在风中等你
我在风中等你 2020-11-22 03:41
  1. How do I return a base64 encoded string given a string?

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

10条回答
  •  梦如初夏
    2020-11-22 04:26

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

提交回复
热议问题