1. 程式人生 > >C# MD5校驗

C# MD5校驗

[] stream mode ssa 進制 new null byte[] 表示

1.方法1

private static string GetMD5HashFromFile(string fileName)
 {
 try
 {
 FileStream file = new FileStream(fileName, FileMode.Open);
 System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.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);
 }
 }
2.方法2

//計算文件的MD5碼

private string getMD5Hash(string pathName)

{

string strResult = "";

string strHashData = "";

byte[] arrbytHashValue;

System.IO.FileStream oFileStream = null;

System.Security.Cryptography.MD5CryptoServiceProvider oMD5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider();

    try

{

oFileStream = new System.IO.FileStream(pathName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite));

arrbytHashValue = oMD5Hasher.ComputeHash(oFileStream);//計算指定Stream 對象的哈希值

oFileStream.Close();

//由以連字符分隔的十六進制對構成的String,其中每一對表示value 中對應的元素;例如“F-2C-4A”

strHashData = System.BitConverter.ToString(arrbytHashValue);

//替換-

strHashData = strHashData.Replace("-", "");

strResult = strHashData;

}

catch (System.Exception ex)

{

MessageBox.Show(ex.Message);

     }

return strResult;

}

3.比較。

方法1和方法2雖然都能計算文件的MD5,但是方法2在針對大文件時,更快,所以更好。

C# MD5校驗