65.9K
CodeProject 正在变化。 阅读更多。
Home

获取任何文件的 MD5 和 SHA-1 (SHA1)

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.62/5 (40投票s)

2005年2月11日

MIT
viewsIcon

138589

downloadIcon

2809

获取文件的哈希值 (SHA-1, MD5) - 此程序需要 .NET Framework 1.1。

Sample Image - DT_File_Hasher.jpg

引言

使用此程序,单击“打开文件”后,您可以选择任何文件,然后单击“打开”按钮,将获得 MD5 和 SHA-1 (SHA1) 文件的哈希值。此程序对于想要获取和保存重要文件哈希值的人非常有用。您需要注意,如果有人更改了文件的哪怕一小部分内容,文件的哈希值也会发生变化。所以试试吧,享受它!

对于此应用程序,我创建了一个类来获取 MD5 和 SHA-1 文件的哈希值

namespace IranianExperts
{
 public sealed class DTHasher
 {
  private DTHasher(){}

  private static byte[] ConvertStringToByteArray(string data)
  {
   return(new System.Text.UnicodeEncoding()).GetBytes(data);
  }

  private static System.IO.FileStream GetFileStream(string pathName)
  {
   return(new System.IO.FileStream(pathName, System.IO.FileMode.Open, 
             System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite));
  }

  public static string GetSHA1Hash(string pathName)
  {
   string strResult = "";
   string strHashData = "";

   byte[] arrbytHashValue;
   System.IO.FileStream oFileStream = null;

   System.Security.Cryptography.SHA1CryptoServiceProvider oSHA1Hasher=
              new System.Security.Cryptography.SHA1CryptoServiceProvider();

   try
   {
    oFileStream = GetFileStream(pathName);
    arrbytHashValue = oSHA1Hasher.ComputeHash(oFileStream);
    oFileStream.Close();

    strHashData = System.BitConverter.ToString(arrbytHashValue);
    strHashData = strHashData.Replace("-", "");
    strResult = strHashData;
   }
   catch(System.Exception ex)
   {
    System.Windows.Forms.MessageBox.Show(ex.Message, "Error!", 
             System.Windows.Forms.MessageBoxButtons.OK, 
             System.Windows.Forms.MessageBoxIcon.Error, 
             System.Windows.Forms.MessageBoxDefaultButton.Button1);
   }

   return(strResult);
  }

  public static 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 = GetFileStream(pathName);
    arrbytHashValue = oMD5Hasher.ComputeHash(oFileStream);
    oFileStream.Close();

    strHashData = System.BitConverter.ToString(arrbytHashValue);
    strHashData = strHashData.Replace("-", "");
    strResult = strHashData;
   }
   catch(System.Exception ex)
   {
    System.Windows.Forms.MessageBox.Show(ex.Message, "Error!", 
               System.Windows.Forms.MessageBoxButtons.OK, 
               System.Windows.Forms.MessageBoxIcon.Error, 
               System.Windows.Forms.MessageBoxDefaultButton.Button1);
   }

   return(strResult);
  }
 }
}
© . All rights reserved.