日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > C# >内容正文

C#

C# MD5摘要算法、哈希算法

發(fā)布時(shí)間:2024/9/20 C# 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C# MD5摘要算法、哈希算法 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

MD5即Message-Digest Algorithm 5(信息-摘要算法5),用于確保信息傳輸完整一致。是計(jì)算機(jī)廣泛使用的雜湊算法之一(又譯摘要算法、哈希算法)

MD5算法具有以下特點(diǎn):

1、壓縮性:任意長度的數(shù)據(jù),算出的MD5值長度都是固定的。

2、容易計(jì)算:從原數(shù)據(jù)計(jì)算出MD5值很容易。

3、抗修改性:對(duì)原數(shù)據(jù)進(jìn)行任何改動(dòng),哪怕只修改1個(gè)字節(jié),所得到的MD5值都有很大區(qū)別。

4、弱抗碰撞:已知原數(shù)據(jù)和其MD5值,想找到一個(gè)具有相同MD5值的數(shù)據(jù)(即偽造數(shù)據(jù))是非常困難的。

5、強(qiáng)抗碰撞:想找到兩個(gè)不同的數(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值對(duì)比

// 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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。