C# MD5摘要算法、哈希算法
生活随笔
收集整理的這篇文章主要介紹了
C# MD5摘要算法、哈希算法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
MD5即Message-Digest Algorithm 5(信息-摘要算法5),用于確保信息傳輸完整一致。是計算機廣泛使用的雜湊算法之一(又譯摘要算法、哈希算法)
MD5算法具有以下特點:
1、壓縮性:任意長度的數(shù)據(jù),算出的MD5值長度都是固定的。
2、容易計算:從原數(shù)據(jù)計算出MD5值很容易。
3、抗修改性:對原數(shù)據(jù)進行任何改動,哪怕只修改1個字節(jié),所得到的MD5值都有很大區(qū)別。
4、弱抗碰撞:已知原數(shù)據(jù)和其MD5值,想找到一個具有相同MD5值的數(shù)據(jù)(即偽造數(shù)據(jù))是非常困難的。
5、強抗碰撞:想找到兩個不同的數(shù)據(jù),使它們具有相同的MD5值,是非常困難的。
通過文件路徑得到文件MD5值?
public static string GetMD5HashFromFile(string fileName){try{FileStream file = new FileStream(fileName, FileMode.Open);System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.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){throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);}}通過流路徑得到MD5值
public static string GetMd5Hash(Stream input){MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();byte[] data = md5Hasher.ComputeHash(input);input.Seek(0, SeekOrigin.Begin);StringBuilder sBuilder = new StringBuilder();for (int i = 0; i < data.Length; i++){sBuilder.Append(data[i].ToString("x2"));}return sBuilder.ToString();}測試發(fā)現(xiàn):通過文件流去得到MD5值,改變了文件的后綴名是沒有區(qū)別的。
字符串MD5值
public static string GetMd5Hash(string input){// Create a new instance of the MD5CryptoServiceProvider object.MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();// Convert the input string to a byte array and compute the hash.byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));// Create a new Stringbuilder to collect the bytes// and create a string.StringBuilder sBuilder = new StringBuilder();// Loop through each byte of the hashed data // and format each one as a hexadecimal string.for (int i = 0; i < data.Length; i++){sBuilder.Append(data[i].ToString("x2"));}// Return the hexadecimal string.return sBuilder.ToString();}字符串MD5值對比
// Verify a hash against a string. md5值不區(qū)分大小寫public static bool VerifyMd5Hash(string input, string hash){// Hash the input.string hashOfInput = getMd5Hash(input);// Create a StringComparer an compare the hashes.StringComparer comparer = StringComparer.OrdinalIgnoreCase;if (0 == comparer.Compare(hashOfInput, hash)){return true;}else{return false;}}總結(jié)
以上是生活随笔為你收集整理的C# MD5摘要算法、哈希算法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: fsc认证的桐木板有吗
- 下一篇: 阳台适合铺贴哪种瓷砖?阳台装修先封阳台还