1
1
// Copyright (c) .NET Foundation. All rights reserved.
2
2
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3
3
4
- using System ;
5
- using System . Text ;
6
- using Microsoft . Extensions . Primitives ;
7
-
8
4
namespace Microsoft . AspNetCore . WebUtilities
9
5
{
10
6
public static class Base64UrlTextEncoder
@@ -17,8 +13,7 @@ public static class Base64UrlTextEncoder
17
13
/// <returns>Base64 encoded string modified with non-URL encodable characters</returns>
18
14
public static string Encode ( byte [ ] data )
19
15
{
20
- var encodedValue = Convert . ToBase64String ( data ) ;
21
- return EncodeInternal ( encodedValue ) ;
16
+ return WebEncoders . Base64UrlEncode ( data ) ;
22
17
}
23
18
24
19
/// <summary>
@@ -29,76 +24,7 @@ public static string Encode(byte[] data)
29
24
/// <returns>The decoded data.</returns>
30
25
public static byte [ ] Decode ( string text )
31
26
{
32
- return Convert . FromBase64String ( DecodeToBase64String ( text ) ) ;
33
- }
34
-
35
- // To enable unit testing
36
- internal static string EncodeInternal ( string base64EncodedString )
37
- {
38
- var length = base64EncodedString . Length ;
39
- while ( length > 0 && base64EncodedString [ length - 1 ] == '=' )
40
- {
41
- length -- ;
42
- }
43
-
44
- if ( length == 0 )
45
- {
46
- return string . Empty ;
47
- }
48
-
49
- var inplaceStringBuilder = new InplaceStringBuilder ( length ) ;
50
- for ( var i = 0 ; i < length ; i ++ )
51
- {
52
- if ( base64EncodedString [ i ] == '+' )
53
- {
54
- inplaceStringBuilder . Append ( '-' ) ;
55
- }
56
- else if ( base64EncodedString [ i ] == '/' )
57
- {
58
- inplaceStringBuilder . Append ( '_' ) ;
59
- }
60
- else
61
- {
62
- inplaceStringBuilder . Append ( base64EncodedString [ i ] ) ;
63
- }
64
- }
65
-
66
- return inplaceStringBuilder . ToString ( ) ;
67
- }
68
-
69
- // To enable unit testing
70
- internal static string DecodeToBase64String ( string text )
71
- {
72
- if ( string . IsNullOrEmpty ( text ) )
73
- {
74
- return text ;
75
- }
76
-
77
- var padLength = 3 - ( ( text . Length + 3 ) % 4 ) ;
78
- var inplaceStringBuilder = new InplaceStringBuilder ( capacity : text . Length + padLength ) ;
79
-
80
- for ( var i = 0 ; i < text . Length ; i ++ )
81
- {
82
- if ( text [ i ] == '-' )
83
- {
84
- inplaceStringBuilder . Append ( '+' ) ;
85
- }
86
- else if ( text [ i ] == '_' )
87
- {
88
- inplaceStringBuilder . Append ( '/' ) ;
89
- }
90
- else
91
- {
92
- inplaceStringBuilder . Append ( text [ i ] ) ;
93
- }
94
- }
95
-
96
- for ( var i = 0 ; i < padLength ; i ++ )
97
- {
98
- inplaceStringBuilder . Append ( '=' ) ;
99
- }
100
-
101
- return inplaceStringBuilder . ToString ( ) ;
27
+ return WebEncoders . Base64UrlDecode ( text ) ;
102
28
}
103
29
}
104
30
}
0 commit comments