码迷,mamicode.com
首页 > 其他好文 > 详细

FormsAuthentication.HashPasswordForStoringInConfigFile 的替代方法

时间:2015-01-30 16:58:53      阅读:395      评论:0      收藏:0      [点我收藏+]

标签:

由于项目中要和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

FormsAuthentication.HashPasswordForStoringInConfigFile 的替代方法

标签:

原文地址:http://www.cnblogs.com/w3live/p/4262448.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!