Skip to content
This repository was archived by the owner on Nov 20, 2018. It is now read-only.

Commit 4dcde8a

Browse files
committed
Added Base64UrlTextEncoder utility from Security repo
1 parent 1ff417f commit 4dcde8a

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
4+
using System;
5+
6+
namespace Microsoft.AspNetCore.WebUtilities
7+
{
8+
public static class Base64UrlTextEncoder
9+
{
10+
/// <summary>
11+
/// Encodes supplied data into Base64 and replaces any URL encodable characters into non-URL encodable
12+
/// characters.
13+
/// </summary>
14+
/// <param name="data">Data to be encoded.</param>
15+
/// <returns>Base64 encoded string modified with non-URL encodable characters</returns>
16+
public static string Encode(byte[] data)
17+
{
18+
return Convert.ToBase64String(data).TrimEnd('=').Replace('+', '-').Replace('/', '_');
19+
}
20+
21+
/// <summary>
22+
/// Decodes supplied string by replacing the non-URL encodable characters with URL encodable characters and
23+
/// then decodes the Base64 string.
24+
/// </summary>
25+
/// <param name="text">The string to be decoded.</param>
26+
/// <returns>The decoded data.</returns>
27+
public static byte[] Decode(string text)
28+
{
29+
return Convert.FromBase64String(Pad(text.Replace('-', '+').Replace('_', '/')));
30+
}
31+
32+
private static string Pad(string text)
33+
{
34+
var padding = 3 - ((text.Length + 3) % 4);
35+
if (padding == 0)
36+
{
37+
return text;
38+
}
39+
return text + new string('=', padding);
40+
}
41+
}
42+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
4+
using Xunit;
5+
6+
namespace Microsoft.AspNetCore.WebUtilities
7+
{
8+
public class Base64UrlTextEncoderTests
9+
{
10+
[Fact]
11+
public void DataOfVariousLengthRoundTripCorrectly()
12+
{
13+
for (int length = 0; length != 256; ++length)
14+
{
15+
var data = new byte[length];
16+
for (int index = 0; index != length; ++index)
17+
{
18+
data[index] = (byte)(5 + length + (index * 23));
19+
}
20+
string text = Base64UrlTextEncoder.Encode(data);
21+
byte[] result = Base64UrlTextEncoder.Decode(text);
22+
23+
for (int index = 0; index != length; ++index)
24+
{
25+
Assert.Equal(data[index], result[index]);
26+
}
27+
}
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)