Skip to content
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions archive/c/c-sharp/Base64EncodeDecode.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using System.Text;

public class Base64EncodeDecode
{
public static void Usage()
{
Console.WriteLine("Usage: please provide a mode and a string to encode/decode");
Environment.Exit(1);
}

public static bool IsBase64Char(char c)
{
return (c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') ||
c == '+' || c == '/' || c == '=';
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function doesn't seem to be used, so it can be removed.


private static bool IsValidBase64(string input)
{
if (string.IsNullOrWhiteSpace(input) || input.Length % 4 != 0)
return false;

foreach (char c in input)
{
if (!"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".Contains(c))
return false;
}

int padCount = input.EndsWith("==") ? 2 :
input.EndsWith('=') ? 1 : 0;

int firstPadIndex = input.IndexOf('=');
return firstPadIndex == -1 || firstPadIndex >= input.Length - padCount;
}

public static int Main(string[] args)
{
if (args.Length != 2)
{
Usage();
return 1;
}

string mode = args[0].ToLowerInvariant();
string value = args[1];

if (string.IsNullOrWhiteSpace(mode) || string.IsNullOrWhiteSpace(value))
{
Usage();
return 1;
}

try
{
string result = mode switch
{
"encode" => Convert.ToBase64String(Encoding.UTF8.GetBytes(value)),
"decode" => IsValidBase64(value)
? Encoding.UTF8.GetString(Convert.FromBase64String(value))
: throw new ArgumentException("Input is not valid Base64."),
_ => throw new ArgumentException("Unknown mode. Use 'encode' or 'decode'.")
};

Console.WriteLine(result);
return 0;
}
catch
{
Usage();
return 1;
}
}
}