获取一个文件的MD5值的作用是测定该文件是否是原文件,以保证文件不曾被恶意更改。
比如我压缩了一个test.zip文件,计算了一个MD5值放到了一个md5.txt文件中。然后把test.zip和md5.txt一起放到了共享文件夹,这时候某个坏人把共享文件夹里面的test.zip解压缩之后放了个木马进去,然后重新压缩成test.zip文件,替换了原来的test.zip(这时候test.zip计算出来的MD5值和原来的已经不一样了)。
想想是不是很吓人,但我们有MD5值计算对比的话就不会被坏人坑。我们先把test.zip文件下载到本地,然后计算其MD5值,然后和md5.txt里面的MD5值比较,如果不一样则判定共享文件夹里面的test.zip有问题。
下面是我写的小例子(工程为c#Windows窗体应用程序):
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
namespace GetMd5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
dlg.InitialDirectory = "D:\\";
dlg.Filter = "压缩文件|*.zip|所有文件|*.*";
dlg.RestoreDirectory = false;//若为false,则打开对话框后为上次的目录。若为true,则为初始目录
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) //选择打开新任务
{
textBox1.Text = System.IO.Path.GetFullPath(dlg.FileName);//将选中的文件的路径传递给TextBox “FilePath”
textBox2.Text = GetMD5HashFromFile(textBox1.Text);
}
}
public string GetMD5HashFromFile(string fileName)
{
try
{
FileStream file = new FileStream(fileName, System.IO.FileMode.Open);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(file);
file.Close();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
catch (Exception ex)
{
throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
}
}
}
}