using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Linq;
namespace Wayne.FDCPOSLibrary
{
public class MD5Crypter
{
System.Security.Cryptography.MD5CryptoServiceProvider cryptic;
public static string passphrase = "DresserFusion}123";
public MD5Crypter()
{
cryptic = new System.Security.Cryptography.MD5CryptoServiceProvider();
cryptic.Initialize();
}
public byte[] getPassphrase()
{
return System.Text.Encoding.ASCII.GetBytes(MD5Crypter.passphrase);
//return UTF8Encoding.UTF8.GetBytes(MD5Crypter.passphrase);
}
///
///
///
///
/// hex string
public string getMD5Hash(string myString)
{
byte[] data = System.Text.Encoding.UTF8.GetBytes(myString);
//byte[] data = UTF8Encoding.UTF8.GetBytes(myString);
var hashBytes = cryptic.ComputeHash(data);
return hashBytes.Select(h => h.ToString("x2")).Aggregate((acc, n) => acc + n);
//return UTF8Encoding.UTF8.GetString(data, 0, data.GetLength(0));
}
public string getMD5Hash(byte[] data)
{
data = cryptic.ComputeHash(data);
return System.Text.Encoding.ASCII.GetString(data, 0, data.GetLength(0));
//return UTF8Encoding.UTF8.GetString(data, 0, data.GetLength(0));
}
public byte[] ComputeHash(byte[] data)
{
return cryptic.ComputeHash(data);
}
// Hash an input string and return the hash as
// a 32 character hexadecimal string.
//public string getMd5Hash(string input)
//{
// // Create a new instance of the MD5CryptoServiceProvider object.
// MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
// // Convert the input string to a byte array and compute the hash.
// byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
// // Create a new Stringbuilder to collect the bytes
// // and create a string.
// StringBuilder sBuilder = new StringBuilder();
// // Loop through each byte of the hashed data
// // and format each one as a hexadecimal string.
// for (int i = 0; i < data.Length; i++)
// {
// sBuilder.Append(data[i].ToString("x2"));
// }
// // Return the hexadecimal string.
// return sBuilder.ToString();
//}
///
/// Verify a hash against a string.
///
///
/// hex string, may contains unreadable char
///
public bool verifyMD5Hash(string input, string expectingHashHexBytesString)
{
// Hash the input.
string hashOfInput = getMD5Hash(input);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, expectingHashHexBytesString))
{
return true;
}
else
{
return false;
}
}
}
}