File tree Expand file tree Collapse file tree 1 file changed +67
-0
lines changed
Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change 1+ using System . Text ;
2+
3+ public class Base64EncodeDecode
4+ {
5+ public static void Usage ( )
6+ {
7+ Console . WriteLine ( "Usage: please provide a mode and a string to encode/decode" ) ;
8+ Environment . Exit ( 1 ) ;
9+ }
10+
11+
12+ private static bool IsValidBase64 ( string input )
13+ {
14+ if ( string . IsNullOrWhiteSpace ( input ) || input . Length % 4 != 0 )
15+ return false ;
16+
17+ foreach ( char c in input )
18+ {
19+ if ( ! "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" . Contains ( c ) )
20+ return false ;
21+ }
22+
23+ int padCount = input . EndsWith ( "==" ) ? 2 :
24+ input . EndsWith ( '=' ) ? 1 : 0 ;
25+
26+ int firstPadIndex = input . IndexOf ( '=' ) ;
27+ return firstPadIndex == - 1 || firstPadIndex >= input . Length - padCount ;
28+ }
29+
30+ public static int Main ( string [ ] args )
31+ {
32+ if ( args . Length != 2 )
33+ {
34+ Usage ( ) ;
35+ return 1 ;
36+ }
37+
38+ string mode = args [ 0 ] . ToLowerInvariant ( ) ;
39+ string value = args [ 1 ] ;
40+
41+ if ( string . IsNullOrWhiteSpace ( mode ) || string . IsNullOrWhiteSpace ( value ) )
42+ {
43+ Usage ( ) ;
44+ return 1 ;
45+ }
46+
47+ try
48+ {
49+ string result = mode switch
50+ {
51+ "encode" => Convert . ToBase64String ( Encoding . UTF8 . GetBytes ( value ) ) ,
52+ "decode" => IsValidBase64 ( value )
53+ ? Encoding . UTF8 . GetString ( Convert . FromBase64String ( value ) )
54+ : throw new ArgumentException ( "Input is not valid Base64." ) ,
55+ _ => throw new ArgumentException ( "Unknown mode. Use 'encode' or 'decode'." )
56+ } ;
57+
58+ Console . WriteLine ( result ) ;
59+ return 0 ;
60+ }
61+ catch
62+ {
63+ Usage ( ) ;
64+ return 1 ;
65+ }
66+ }
67+ }
You can’t perform that action at this time.
0 commit comments