Несмотря на то, что данная тема не секретная и можно найти достаточно много примеров о том, как работать с MD5, я все-таки решил написать реализацию этого замечательного процесса.
Для начала добавим в код следующее пространство имен:
Для начала добавим в код следующее пространство имен:
using System.Security.Cryptography;
Для того, чтобы получить MD5 файла, напишем следующий метод:
public static string GetHashFromFile(string fileName)
{
FileStream file = new FileStream(fileName, 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();
}
Сохранить MD5 в файл:
public static void saveHashFile(string hashString)
{
try
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)
+ @"\File.MD5", false))
{
file.WriteLine(hashString);
file.Close();
}
}
catch (SystemException ex)
{
}
}
Прочитать хэш из файла:
private static string readHashFile()
{
try
{
using (System.IO.StreamReader file = new System.IO.StreamReader(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)
+ @"\File.MD5", false))
{
string fileString = file.ReadLine();
file.Close();
return fileString;
}
}
catch (SystemException ex)
{
EventLog.WriteEntry("Contract Checker", ex.Message, EventLogEntryType.Error, 101);
return "file not read";
}
}
А теперь сравним две чексуммы:
public static bool verifyMd5Hash(string newMD5)
{
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(readHashFile(), newMD5))
{
return true;
}
else
{
return false;
}
}
Комментариев нет:
Отправить комментарий