C#: base64url according to RFC4648
Asked Answered
M

1

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"

Mariomariology answered 4/11, 2014 at 9:53 Comment(7)
Rather than just say "it looks like" can you give an example of what it does vs what you'd expect?Bilbao
@JonSkeet: I'm sorry. I just added my concerns...Mariomariology
It's still fairly vague. Please give a concrete example: sample code containing sample data, with the actual output and expected output. Please read tinyurl.com/stack-hintsBilbao
@JonSkeet: OK, I added an example with the expected outcome.Mariomariology
Right, that's more like it.Bilbao
Simple solution - just remove the last character of the result using Substring. Anything wrong with that?Bilbao
@JonSkeet: Nope, sounds great. I was confused because it's not documented on the Microsoft page...Mariomariology
B
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 :(

Bilbao answered 4/11, 2014 at 12:45 Comment(4)
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);Mariomariology
@Dunken: I believe you should add it regardless of the length - but with 0 instead of 4, if it would otherwise be 4.Bilbao
Added gist Base64UrlExtensions, hope this is useful to anyone. This has both encode and decode as extensions on string.Detestation
@Detestation doesn't seem to work in .NET Core, the HttpServerUtility doesn't exist there.Turbo

© 2022 - 2024 — McMap. All rights reserved.