原文: C#中将字元串轉換成Md5值的方法 版權聲明:有問題可聯系部落客QQ:15577969,大家一起互相交流和學習。 https://blog.csdn.net/qq15577969/article/details/79518724
資料庫中的密碼為Md5加密格式,md5是不可以逆轉換的,是以隻能比較Md5值 //查詢管理登入的語句,其中c3284d0f94606de1fd2af172aba15bf3為admin的【二次Md5值】(經過2次md5轉換而得的字元串) select COUNT(*) from sys_admin where login_name='admin' and login_pwd='c3284d0f94606de1fd2af172aba15bf3' 1、引入庫 using System.Security.Cryptography;//引用Md5轉換功能 2、計算字元串的Md5值 public static string GetMD5WithString(String input) { MD5 md5Hash = MD5.Create(); // 将輸入字元串轉換為位元組數組并計算哈希資料 byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); // 建立一個 Stringbuilder 來收集位元組并建立字元串 StringBuilder str = new StringBuilder(); // 循環周遊哈希資料的每一個位元組并格式化為十六進制字元串 for (int i = 0; i < data.Length; i++) { str.Append(data[i].ToString("x2"));//加密結果"x2"結果為32位,"x3"結果為48位,"x4"結果為64位 } // 傳回十六進制字元串 return str.ToString(); } 3、計算檔案的Md5值 static public string GetMD5WithFilePath(string filePath) { FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] hash_byte = md5.ComputeHash(file); string str = System.BitConverter.ToString(hash_byte); str = str.Replace("-", ""); return str; } |