8

I'm looking for a (fast) standard implementation for base64url according to RFC4648 in C#.

I found HttpServerUtility.UrlTokenEncode but it looks like this doesn't follow RFC4648 (UrlTokenEncode adds a number at the end which indicates the number of = signs that were removed; see here and here).

Example:

base64 encoding:

Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes("AA")); //returns "QUE="

base64url encoding:

HttpServerUtility.UrlTokenEncode(System.Text.Encoding.ASCII.GetBytes("AA")); //returns "QUE1" but I would expect "QUE"

Community
  • 1
  • 1
Dunken
  • 8,481
  • 7
  • 54
  • 87

1 Answers1

9

Based on the comments, it sounds like System.Web.HttpServerUtility.UrlTokenEncode does the right thing except for the extra character for padding. So you should be able to do:

string customBase64 = HttpServerUtility.UrlTokenEncode(data);
string rfc4648 = customBase64.Substring(0, customBase64.Length - 1);

However, you should add unit tests to check that it really does use the RFC 4648 alphabet (and in the same way as RFC 4648). It's somewhat surprising that the docs are so sparse :(

Waldemar Gałęzinowski
  • 1,125
  • 1
  • 10
  • 18
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    In case you want to decode (`UrlTokenDecode`) Jon's `rfc4648` you need to add the extra character again: `if (rfc4648.Length%4 != 0) rfc4648 += (4 - rfc4648.Length%4);` – Dunken Nov 04 '14 at 13:55
  • 1
    @Dunken: I believe you should add it regardless of the length - but with 0 instead of 4, if it would otherwise be 4. – Jon Skeet Nov 04 '14 at 14:01
  • 4
    Added gist [Base64UrlExtensions](https://gist.github.com/dariusdamalakas/b9570c36481aea6dd24d), hope this is useful to anyone. This has both encode and decode as extensions on `string`. – Darius Nov 18 '15 at 08:10
  • 1
    @Darius doesn't seem to work in .NET Core, the HttpServerUtility doesn't exist there. – Matt Apr 16 '20 at 17:35