zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    以后努力,每天写博客!
    无题
    Fainting
    明天任务
    hdu 4022 Bombing(map)
    codeforces 1216E1 Numerical Sequence (easy version) (前缀和/二分)
    CodeForces 1176E Cover it!
    codeforces 1234D Distinct Characters Queries
    codeforces 1249C2 Good Numbers (hard version)
    codeforces 913B Christmas Spruce(树)
  • 原文地址:https://www.cnblogs.com/w3live/p/4262448.html
Copyright © 2011-2022 走看看