using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace FilterAPI.External
{
    public class ExecutingHash
    {
        public static String GetMD5OfExE(String Path) { return MD5(GetBytesOfExE(Path)); }

        //https://stackoverflow.com/questions/8875296/how-do-i-get-the-hash-of-current-exe
        public static string GetExecutingFileHash()
        {
            return MD5(GetBytesOfExE(string.Concat(AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.FriendlyName)));
        }

        private static string MD5(byte[] input)
        {
            return MD5(ASCIIEncoding.ASCII.GetString(input));
        }

        private static string MD5(string input)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

            byte[] originalBytes = ASCIIEncoding.Default.GetBytes(input);
            byte[] encodedBytes = md5.ComputeHash(originalBytes);

            return BitConverter.ToString(encodedBytes).Replace("-", "");
        }

        private static byte[] GetBytesOfExE(string path)
        {
            FileStream running = File.OpenRead(path);

            byte[] exeBytes = new byte[running.Length];
            running.Read(exeBytes, 0, exeBytes.Length);

            running.Close();

            return exeBytes;
        }
    }
}
