Skip to content

Instantly share code, notes, and snippets.

@gerektoolhy
Last active December 15, 2017 15:37
Show Gist options
  • Save gerektoolhy/b9570c36481aea6dd24d to your computer and use it in GitHub Desktop.
Save gerektoolhy/b9570c36481aea6dd24d to your computer and use it in GitHub Desktop.
Base64UrlExtensions as specified by rfc4648 ((https://tools.ietf.org/html/rfc4648#section-5)
public static class Base64UrlExtensions
{
/// <summary>
/// Encodes string to base64url, as specified by rfc4648 (https://tools.ietf.org/html/rfc4648#section-5)
/// </summary>
/// <returns></returns>
public static string ToBase64Url(this string str)
{
// TODO - adds reference to System.Web
if (str == null)
throw new ArgumentNullException("str");
var customBase64 = HttpServerUtility.UrlTokenEncode(Encoding.UTF8.GetBytes(str));
return customBase64.Length == 0 ? customBase64 : customBase64.Substring(0, customBase64.Length - 1);
}
public static string FromBase64Url(this string rfc4648)
{
if (rfc4648.Length%4 != 0)
rfc4648 += (4 - rfc4648.Length%4);
else
rfc4648 += 0;
return Encoding.UTF8.GetString(HttpServerUtility.UrlTokenDecode(rfc4648));
}
}
[TestFixture]
public class Base64UrlExtensionsTest
{
[TestCase("a", "YQ")] // basic string handling
[TestCase("", "")] // empty string handling
[TestCase("123", "MTIz")] // byte array length equal to 4
[TestCase("12345678901234567890", "MTIzNDU2Nzg5MDEyMzQ1Njc4OTA")] // longer string handling
[Test]
public void Convert(string str, string expected)
{
// Given, When, Then
Assert.That(str.ToBase64Url(), Is.EqualTo(expected) );
Assert.That(str.ToBase64Url().FromBase64Url(), Is.EqualTo(str));
// Given, When, Then
Assert.That(expected.FromBase64Url(), Is.EqualTo(str));
Assert.That(expected.FromBase64Url().ToBase64Url(), Is.EqualTo(expected));
}
[TestCase(null)]
public void NullHandling(string str)
{
// Given, When, Then
Assert.Throws(Is.TypeOf<ArgumentNullException>()
.And.Message.Contains("str"), () => str.ToBase64Url());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment