This repository was archived by the owner on Nov 20, 2018. It is now read-only.
File tree Expand file tree Collapse file tree 2 files changed +72
-0
lines changed
src/Microsoft.AspNetCore.WebUtilities
test/Microsoft.AspNetCore.WebUtilities.Tests Expand file tree Collapse file tree 2 files changed +72
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments