My KISS, решение, которое работает на netstandard1.6
:
public static class Utils
{
private static readonly Regex InvalidBase64UrlTokens = new Regex(
@"[^=a-z0-9]",
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
public static string Base64UrlTokenEncode(byte[] data)
{
var padding = 0;
var base64String = Convert.ToBase64String(data);
return InvalidBase64UrlTokens.Replace(base64String, m => {
switch (m.Value)
{
case "+": return "-";
case "=":
padding++;
return "";
default: return "_";
}
}) + padding;
}
}
Пройдены следующие тесты Nunit:
[TestFixture]
public class Base64UrlTokenEncodingTests
{
private static IEnumerable<TestCaseData> CompareAgainstSystemWebImplementationCases()
{
var random = new Random(42);
for (var i = 0; i < 100; i++)
{
var bytes = new byte[i + 1];
random.NextBytes(bytes);
var name = Convert.ToBase64String(bytes);
var systemWeb = System.Web.HttpServerUtility.UrlTokenEncode(bytes);
yield return new TestCaseData(bytes).SetName(name).Returns(systemWeb);
}
}
[TestCaseSource(nameof(CompareAgainstSystemWebImplementationCases))]
public string CompareAgainstSystemWebImplementation(byte[] data) =>
Utils.Base64UrlTokenEncode(data);
}