生成软件hash值:
private string GetEXEHashString()
{
//获得软件哈希值
Process currProcess = Process.GetCurrentProcess();
string filePath = currProcess.MainModule.FileName;
string hashEXE = string.Empty;
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
// hash 算法
MD5 algorithm = MD5.Create();
byte[] hashData = algorithm.ComputeHash(fs);
hashEXE = ByteArrayToHexString(hashData);
fs.Close();
}
Console.WriteLine(hashEXE.ToString());
Info("GetEXEHashString :hashEXE = " + hashEXE.ToString());
return hashEXE.ToString();
}
private static string ByteArrayToHexString(byte[] bytes)
{
int length = bytes.Length;
StringBuilder sb = new StringBuilder();
foreach (byte data in bytes)
{
sb.Append(data.ToString("x2"));
}
return sb.ToString();
}
生成文件hash值
public static String ComputeMD5(String fileName)
{
String hashMD5 = String.Empty;
//检查文件是否存在,如果文件存在则进行计算,否则返回空值
if (System.IO.File.Exists(fileName))
{
using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
//计算文件的MD5值
System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create();
Byte[] buffer = calculator.ComputeHash(fs);
calculator.Clear();
//将字节数组转换成十六进制的字符串形式
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < buffer.Length; i++)
{
stringBuilder.Append(buffer[i].ToString("x2"));
}
hashMD5 = stringBuilder.ToString();
}//关闭文件流
}//结束计算
return hashMD5;
}//ComputeMD5