How do I get the hash of current .exe?

前端 未结 4 380
被撕碎了的回忆
被撕碎了的回忆 2021-01-03 05:45

[SOLVED]: I copied the file and ran the hasher on that copy.

I need my app to find the EXE\'s current MD5. I can get the MD5 of any file. However, n

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-03 06:52

    Since I've tried these answers and found that none of them change every edit to the exe, or change at all, I found something that actually does work.

    I did not edit any code here, all of this was from the referred page below.

    Reference: http://www.vcskicks.com/self-hashing.php

    internal static class ExecutingHash
    {
        public static string GetExecutingFileHash()
        {
            return MD5(GetSelfBytes());
        }
    
        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[] GetSelfBytes()
        {
            string path = Application.ExecutablePath;
    
            FileStream running = File.OpenRead(path);
    
            byte[] exeBytes = new byte[running.Length];
            running.Read(exeBytes, 0, exeBytes.Length);
    
            running.Close();
    
            return exeBytes;
        }
    }
    

    Every test seems to output properly. I'd recommend to anyone seeing this to use this class or make something of it.

提交回复
热议问题