Skip to main content

C# helper methods to encode and decode Base64 values.

public static class Base64Url
{
    public static string Encode(byte[] input)
    {
        var output = Convert.ToBase64String(input);

        output = output.Split('=')[0]; // Remove any trailing '='s
        output = output.Replace('+', '-'); // 62nd char of encoding
        output = output.Replace('/', '_'); // 63rd char of encoding

        return output;
    }

    public static byte[] Decode(string input)
    {
        var output = input;

        output = output.Replace('-', '+'); // 62nd char of encoding
        output = output.Replace('_', '/'); // 63rd char of encoding

        switch (output.Length % 4) // Pad with trailing '='s
        {
            case 0:
                break; // No pad chars in this case
            case 2:
                output += "==";
                break; // Two pad chars
            case 3:
                output += "=";
                break; // One pad char
            default:
                throw new ArgumentOutOfRangeException(
                    nameof(input), "Illegal base64url string!");
        }

        var converted = Convert.FromBase64String(output); // Standard base64 decoder

        return converted;
    }
}

// -------------------------------------------
// Usage
// -------------------------------------------

// Encode
var bytes1 = new byte[] { 72, 101, 108, 108, 111, 32, 66, 97, 115, 101, 54, 52, 85, 114, 108, 32, 101, 110, 99, 111, 100, 105, 110, 103, 33 };
var encodedString1 = Base64Url.Encode(bytes1);
WriteLine(encodedString1); // SGVsbG8gQmFzZTY0VXJsIGVuY29kaW5nIQ

// Decode
var encodedString2 = "SGVsbG8gQmFzZTY0VXJsIGVuY29kaW5nIQ";
var bytes2 = Base64Url.Decode(encodedString2);
WriteLine(System.Text.Encoding.UTF8.GetString(bytes2)); // Hello Base64Url encoding!

// ---------------------------------------------------------------------------
// or...
// ---------------------------------------------------------------------------

// From
// https://github.com/octokit/octokit.net/blob/master/Octokit/Helpers/StringExtensions.cs
public static string ToBase64String(this string input)
{
    return Convert.ToBase64String(Encoding.UTF8.GetBytes(input));
}

// From
// https://github.com/octokit/octokit.net/blob/master/Octokit/Helpers/StringExtensions.cs
public static string FromBase64String(this string encoded)
{
    var decodedBytes = Convert.FromBase64String(encoded);
    return Encoding.UTF8.GetString(decodedBytes, 0, decodedBytes.Length);
}

// ---------------------------------------------------------------------------
// or...
// ---------------------------------------------------------------------------

using System;
using System.Text;
using System.Text.RegularExpressions;

//
// https://github.com/IdentityModel/Thinktecture.IdentityModel.45/blob/master/IdentityModel/Thinktecture.IdentityModel/Http/HeaderEncoding.cs
//

namespace Thinktecture.IdentityModel.Http
{
    public static class HeaderEncoding
    {
        public static bool IsBase64Encoded(string token)
        {
            token = token.Trim();
            return (token.Length % 4 == 0) &&
                   (Regex.IsMatch(token, @"^[a-zA-Z0-9+/]*={0,3}$", RegexOptions.None));
        }

        public static string EncodeBase64(string token)
        {
            Encoding encoding = Encoding.GetEncoding("iso-8859-1");
            string encodedToken = Convert.ToBase64String(encoding.GetBytes(token));
            return encodedToken;
        }

        public static string DecodeBase64(string token)
        {
            Encoding encoding = Encoding.GetEncoding("iso-8859-1");
            string decodedToken = encoding.GetString(Convert.FromBase64String(token));
            return decodedToken;
        }
    }
}