c#md5与SHA1验证函数
1 /// <summary> 2 /// MD5验证函数 3 /// </summary> 4 /// <param name="fileName">文件的路径</param> 5 /// <param name="blockletter">返回的MD5值是否为大写</param> 6 /// <returns></returns> 7 public static string GetMD5HashFromFile(string fileName,bool blockletter) 8 { 9 try 10 { 11 FileStream file = new FileStream(fileName, FileMode.Open); 12 System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); 13 byte[] retVal = md5.ComputeHash(file); 14 file.Close(); 15 16 StringBuilder sb = new StringBuilder(); 17 for (int i = 0; i < retVal.Length; i++) 18 { 19 if (blockletter) 20 sb.Append(retVal[i].ToString("X2")); 21 else 22 sb.Append(retVal[i].ToString("x2")); 23 } 24 return sb.ToString(); 25 } 26 catch (Exception ex) 27 { 28 return "文件读取错误"; 29 } 30 } 31 /// <summary> 32 /// 计算SHA1值 33 /// </summary> 34 /// <param name="fileName">文件地址</param> 35 /// <param name="blockletter">是否输出大写</param> 36 /// <returns></returns> 37 public static string GetSHA1HashFromFile(string fileName, bool blockletter) 38 { 39 var tragetFile = new System.IO.FileStream(fileName, System.IO.FileMode.Open); 40 var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider(); 41 byte[] hashbytes = sha1.ComputeHash(tragetFile); 42 tragetFile.Close(); 43 44 System.Text.StringBuilder sb = new System.Text.StringBuilder(); 45 for (int i = 0; i < hashbytes.Length; i++) 46 { 47 if (blockletter) //判断输出大小写 48 sb.Append(hashbytes[i].ToString("X2")); 49 else 50 sb.Append(hashbytes[i].ToString("x2")); 51 } 52 return sb.ToString(); 53 }