(1)
using System.Security.Cryptography;
byte[] result = Encoding.Default.GetBytes(yps); //tbPass為輸入密碼的文本框 MD5 md5 = new MD5CryptoServiceProvider(); byte[] output = md5.ComputeHash(result); string str = BitConverter.ToString(output).Replace("-", ""); if(str.Length!=32) System.Diagnostics.Debug.WriteLine("開始調試"); return str;
(2)
using System.Security.Cryptography;
string cl = yps; string pwd = ""; MD5 md5 = MD5.Create();//實例化一個md5對像 // 加密后是一個字節類型的數組,這里要注意編碼UTF8/Unicode等的選擇 byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl)); if (s.Length != 16) System.Diagnostics.Debug.WriteLine("開始調試"); // 通過使用循環,將字節類型的數組轉換為字符串,此字符串是常規字符格式化所得 for (int i = 0; i < s.Length; i++) { // 將得到的字符串使用十六進制類型格式。格式后的字符是小寫的字母,如果使用大寫(X)則格式后的字符是大寫字符 pwd = pwd + s[i].ToString("X"); } if (pwd.Length != 32) System.Diagnostics.Debug.WriteLine("開始調試"); return pwd;
(3)
using System.Web.Security;
password = FormsAuthentication.HashPasswordForStoringInConfigFile(cpassword, "MD5");
上述三種方式的MD5加密,具體原理不知了。說說微小區別
(1)與(3)的Md5值是一樣的。(2)與(1)、(3)的Md5值有微小區別,原因是
pwd = pwd + s[i].ToString("X"); 該語句轉化為16進制時,如果轉化值為一位,比如3等,另外兩種方法此時轉化后的值為03,造成
最后的Md5值小於等於32位,從而造成(2)與(1)、(3)的Md5值不一定相等
所以,如果Md5加密,最好使用同一種方式。