How do I encode and decode a base64 string?

前端 未结 10 2274
我在风中等你
我在风中等你 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:25

    URL safe Base64 Encoding/Decoding

    public static class Base64Url
    {
        public static string Encode(string text)
        {
            return Convert.ToBase64String(Encoding.UTF8.GetBytes(text)).TrimEnd('=').Replace('+', '-')
                .Replace('/', '_');
        }
    
        public static string Decode(string text)
        {
            text = text.Replace('_', '/').Replace('-', '+');
            switch (text.Length % 4)
            {
                case 2:
                    text += "==";
                    break;
                case 3:
                    text += "=";
                    break;
            }
            return Encoding.UTF8.GetString(Convert.FromBase64String(text));
        }
    }
    

提交回复
热议问题