Very useful utility class for base64 conversion


public static class Extensions
{
       static readonly char[] padding = { '=' };

       public static string ToBase64(this byte[] buffer)
       {
            if (buffer == null)
                return string.Empty;

            return Convert.ToBase64String(buffer);
        }

       public static byte[] FromBase64(this string encoded)
       {
            if (string.IsNullOrWhiteSpace(encoded))
                return Array.Empty();

            return Convert.FromBase64String(encoded);
        }

       public static string ToBase64Url(this byte[] buffer)
       {
            if (buffer == null)
                return string.Empty;

            string base64Url = Convert.ToBase64String(buffer)
                .TrimEnd(padding).Replace('+', '-').Replace('/', '_');

            return base64Url;
        }


       public static byte[] FromBase64Url(this string encoded)
       {
            string incoming = encoded.Replace('_', '/').Replace('-', '+');        

            switch (encoded.Length % 4)
            {
                case 2: incoming += "=="; break;
                case 3: incoming += "="; break;
            }

            byte[] bytes = Convert.FromBase64String(incoming);
            return bytes;

        }

    }

Post a Comment

Previous Post Next Post