Skip to content

Instantly share code, notes, and snippets.

@ishahid
Forked from inogo/Hashes.cs
Last active December 13, 2015 17:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ishahid/4948899 to your computer and use it in GitHub Desktop.
Save ishahid/4948899 to your computer and use it in GitHub Desktop.
MD5 and SHA1 hash calculation tool.
using System;
using System.Text;
using System.Security.Cryptography;
static class Hash
{
public static string SHA1(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
var sha1 = new SHA1CryptoServiceProvider();
return BitConverter.ToString(sha1.ComputeHash(buffer)).Replace("-", "");
}
private static string MD5(string text)
{
var md5 = new MD5CryptoServiceProvider();
byte[] data = md5.ComputeHash(Encoding.Default.GetBytes(text));
var sb = new StringBuilder(32);
for (int i = 0; i < data.Length; i++)
sb.Append(data[i].ToString("x2"));
return sb.ToString();
}
private static void PrintUsage(bool full)
{
if (full)
{
Console.WriteLine("Computes MD5 or SHA1 hash of a string.");
Console.WriteLine("https://gist.github.com/ishahid/4948899");
}
Console.WriteLine();
Console.WriteLine("Usage: hash [[OPTION] <string>]");
Console.WriteLine();
Console.WriteLine("Options:");
Console.WriteLine(" -md5 Calculate MD5 hash of the string.");
Console.WriteLine(" Default option if no option is specified.");
Console.WriteLine(" -sha1 Calculate SHA1 hash of the string.");
}
public static int Main(string[] args)
{
string hash = "";
switch(args.Length)
{
case 0:
PrintUsage(true);
break;
case 1:
hash = MD5(args[0]);
Console.WriteLine(hash.ToLower());
break;
case 2:
if (args[0] == "-md5")
{
hash = MD5(args[1]);
Console.WriteLine(hash.ToLower());
} else {
if (args[0] == "-sha1")
{
hash = SHA1(args[1]);
Console.WriteLine(hash.ToLower());
} else {
Console.WriteLine("Invalid switch.");
PrintUsage(false);
}
}
break;
default:
Console.WriteLine("Invalid switch.");
PrintUsage(false);
break;
}
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment