using System;

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);
        }

        public string getMD5Hash(string myString)
        {
            byte[] data = System.Text.Encoding.ASCII.GetBytes(myString);
            //byte[] data = UTF8Encoding.UTF8.GetBytes(myString);
            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 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.
        public bool verifyMD5Hash(string input, string hash)
        {
            // Hash the input.
            string hashOfInput = getMD5Hash(input);

            // Create a StringComparer an compare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(hashOfInput, hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}