FormsAuthentication.HashPasswordForStoringInConfigFile 的替代方法


由於項目中要和php對接,要將一段字符串生成md5(16位)驗證碼,在英文字符時,沒有太大問題,但在遇到中文時,兩邊字條始終不一致。

php是別人的項目,看不到源碼,網上一查,估計是這樣寫的:

<?php   
echo substr(md5("admin"),8,16);  // 16位MD5加密   
echo "<hr>";   
echo md5("admin");    // 32位MD5加密   
?>  

之前的 md5代如下(對md5沒有過多研究,這段代碼也是網上找的):

public static string Md5_16(string str)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(str)), 4, 8);
            t2 = t2.Replace("-", "");
            t2 = t2.ToLower();
            return t2;
        }

在苦惱之際,想到以前還有一種md5的做法,得出的值和php生成的一比對,是正確的。但現在4.5環境下警告該方法過期了

return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();   //32位

return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8, 16);  //16位

本着認真負責的精神,再找找找(剛好也有時間),結果還是在msdn上找到的一段代碼,只不過把 HashPasswordForStoringInConfigFile 這個方法重新實現了下

public static string GetMd5Hash(string input)
        {
            MD5 md5Hash = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.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();
        }

來源鏈接:https://social.msdn.microsoft.com/Forums/zh-TW/590bd6a8-57d7-4041-81da-80fe8b832b77/md5


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM