1. 程式人生 > >c#:通過MD5得到檔案和String的校驗值

c#:通過MD5得到檔案和String的校驗值

得到檔案校驗值

public static string GetMD5HashFromFile(string fileName)
{
      try
      {
           FileStream file = new FileStream(fileName, System.IO.FileMode.Open, FileAccess.Read);
           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) { MyLog(LogPath , "Message " + System.DateTime.Now.ToLongTimeString() +" :"
+ ex.Message);//MessageLog return "no access"; //throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message); } }

得到String校驗值

public static string GetMD5HashFromFile(string strToHash)
{
    try
    {
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] bytes = System.Text
.Encoding.UTF8.GetBytes(strToHash); bytes = md5.ComputeHash(bytes); md5.Clear(); String ret = ""; for (int i = 0; i < bytes.Length; i++) { ret += Convert.ToString(bytes[i], 16).PadLeft(2, '0'); } return ret; } catch (Exception ex) { Console.WriteLine("Message " + System.DateTime.Now.ToLongTimeString() + " :" + ex.Message);//MessageLog return "Md5 Error"; } }