-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathBase64Url.cs
53 lines (47 loc) · 1.71 KB
/
Base64Url.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ryadel.Components.Security
{
/// <summary>
/// Base64Url encoder/decoder
/// </summary>
public static class Base64Url
{
/// <summary>
/// Encodes the specified byte array.
/// </summary>
/// <param name="arg">The argument.</param>
/// <returns></returns>
public static string Encode(byte[] arg)
{
var s = Convert.ToBase64String(arg); // Standard base64 encoder
s = s.Split('=')[0]; // Remove any trailing '='s
s = s.Replace('+', '-'); // 62nd char of encoding
s = s.Replace('/', '_'); // 63rd char of encoding
return s;
}
/// <summary>
/// Decodes the specified string.
/// </summary>
/// <param name="arg">The argument.</param>
/// <returns></returns>
/// <exception cref="System.Exception">Illegal base64url string!</exception>
public static byte[] Decode(string arg)
{
var s = arg;
s = s.Replace('-', '+'); // 62nd char of encoding
s = s.Replace('_', '/'); // 63rd char of encoding
switch (s.Length % 4) // Pad with trailing '='s
{
case 0: break; // No pad chars in this case
case 2: s += "=="; break; // Two pad chars
case 3: s += "="; break; // One pad char
default: throw new Exception("Illegal base64url string!");
}
return Convert.FromBase64String(s); // Standard base64 decoder
}
}
}