【.NET】MD5的用法(對文件、字符串)

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace ConsoleApp_PreventFileTampering
{
class Program
{
static void Main(string[] args)
{
//TestGetFileHash();

TestGetMd5();
}

#region 經過Hash值來驗證文件是否被篡改

public static void TestGetFileHash()
{
string fileHash = "";
while (true)
{
fileHash = GetFileHash(@"C:\error.txt");
Console.WriteLine("文件MD5-HASH值爲:{0}", fileHash);
Console.ReadKey();
//手動修改文件試試,HASH值會變化
//手動將剛纔的修改恢復,HASH值會還原
}
}

/// <summary>
/// 經過Hash值來驗證文件是否被篡改
/// </summary>
/// <param name="argFilePath">文件路徑</param>
/// <returns>輸出Hash值</returns>
public static string GetFileHash(string argFilePath)
{
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
using (FileStream fs = new FileStream(argFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
return BitConverter.ToString(md5.ComputeHash(fs)).Replace("-", "");
}
}

#endregion

#region 對字符串用MD5加密

public static void TestGetMd5()
{
while (true)
{
Console.WriteLine("輸入要加密的字符串:");
string input = Console.ReadLine();
string md5 = GetMd5Hash2(input);
Console.WriteLine("輸出的加密字符串爲:" + md5 + "\r\n");
Console.ReadLine();
}
}

/// <summary>
/// 將字符串轉換成MD5值存儲
/// 【直接使用本方法加密MD5是不安全的,能夠經過窮舉法得到加密前的字符串】
/// </summary>
/// <param name="argInput">輸入的字符串</param>
/// <returns>輸出的MD5值</returns>
public static string GetMd5Hash(string argInput)
{
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
return BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(argInput))).Replace("-", "");
}
}

/// <summary>
/// 屢次使用MD5值以及內部拼hashKey法,增長窮舉破解的難度
/// </summary>
/// <param name="argInput">輸入的字符串</param>
/// <returns>輸出特殊處理過的MD5值</returns>
public static string GetMd5Hash2(string argInput)
{
string hashKey = "Kae@#$@!,.Js+{f>.294oE";
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
string hashCode = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(argInput)))
.Replace("-", "")
+ BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(hashKey)))
.Replace("-", "");

return BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(hashCode))).Replace("-", "");
}
}

#endregion }}
相關文章
相關標籤/搜索