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

转载于:https://www.cnblogs.com/w3live/p/4262448.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值