-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathBase64UrlDecoder.cs
More file actions
78 lines (67 loc) · 2.49 KB
/
Copy pathBase64UrlDecoder.cs
File metadata and controls
78 lines (67 loc) · 2.49 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using System;
using System.Globalization;
using System.Text;
namespace SPOAuthFiddlerExt
{
public class Base64UrlDecoder
{
/// <summary>
/// URL decodes a string.
/// </summary>
/// <param name="arg">The string to decode.</param>
/// <returns>The URL decoded string. </returns>
public static string Decode(string arg)
{
return Encoding.UTF8.GetString(DecodeBytes(arg));
}
/// <summary>
/// URL decodes a string into a byte array
/// </summary>
/// <param name="value">The string to decode</param>
/// <returns>The decoded byte array</returns>
public static byte[] DecodeBytes(string value)
{
const char BASE64_PAD_CHARACTER = '=';
const string DOUBLE_BASE64_PAD_CHARACTER = "==";
const char BASE64_CHARACTER_62 = '+';
const char BASE64URL_CHARACTER_62 = '-';
const char BASE64_CHARACTER_63 = '/';
const char BASE64URL_CHARACTER_63 = '\u005F';
byte[] ret;
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("value", "A null value cannot be decoded.");
}
string convertedValue = value;
//Replace "-" with "+"
convertedValue = convertedValue.Replace(BASE64URL_CHARACTER_62, BASE64_CHARACTER_62);
//Replace the ENQ character with "/"
convertedValue = convertedValue.Replace(BASE64URL_CHARACTER_63, BASE64_CHARACTER_63);
switch (convertedValue.Length % 4)
{
case 0:
{
ret = Convert.FromBase64String(convertedValue);
break;
}
case 2:
{
convertedValue += DOUBLE_BASE64_PAD_CHARACTER;
ret = Convert.FromBase64String(convertedValue);
break;
}
case 3:
{
convertedValue += BASE64_PAD_CHARACTER;
ret = Convert.FromBase64String(convertedValue);
break;
}
default:
{
throw new ArgumentException("Not a valid base64 URL string", value);
}
}
return ret;
}
}
}