• 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

  • 相关阅读:
    jquery easy ui 简单字段选择搜索实现
    (转)EasyUI 分页总结
    EasyUI 搜索框
    微信公众号开发简单介绍
    【POJ3740】Easy Finding DLX(Dancing Links)精确覆盖问题
    推断View是否显示在界面上
    菜鸟调错(八)—— Maven编译错误:不兼容的类型的解决方式
    js对table操作(添加删除交换上下TR)
    NBUT 1222 English Game(trie树+DP)
    Android 返回键的处理
  • 原文地址:https://www.cnblogs.com/w3live/p/4262448.html
Copyright © 2020-2023  润新知