代码之家  ›  专栏  ›  技术社区  ›  John Farrell

如何获取与FormsAuthentication.HashPasswordForToringConfigFile(“asdf”,“md5”)方法相同的哈希?

  •  4
  • John Farrell  · 技术社区  · 14 年前

    正在查找方法或指向正确的方向,以便返回等于 FormsAuthentication.HashPasswordForStoringInConfigFile("asdf", "MD5") . 我一直在尝试这样的代码:

            ASCIIEncoding encoding = new ASCIIEncoding();
            encoding.GetBytes("asdf");
    
            var hashedBytes = MD5.Create().ComputeHash(bytes);
            var password = encoding.GetString(hashedBytes);
    

    我不太擅长散列,所以我不知道下一步该去哪里。我总是以疯狂的特殊字符结尾,而formsauth方法总是返回可读的内容。

    只是试图从一些内部业务类中删除对形式验证的外部依赖。

    5 回复  |  直到 14 年前
        1
  •  9
  •   Aliostad    14 年前

    这是反射镜的输出:

    您的问题不是使用UTF8

    public static string HashPasswordForStoringInConfigFile(string password, string passwordFormat)
    {
        HashAlgorithm algorithm;
        if (password == null)
        {
            throw new ArgumentNullException("password");
        }
        if (passwordFormat == null)
        {
            throw new ArgumentNullException("passwordFormat");
        }
        if (StringUtil.EqualsIgnoreCase(passwordFormat, "sha1"))
        {
            algorithm = SHA1.Create();
        }
        else
        {
            if (!StringUtil.EqualsIgnoreCase(passwordFormat, "md5"))
            {
                throw new ArgumentException(SR.GetString("InvalidArgumentValue", new object[] { "passwordFormat" }));
            }
            algorithm = MD5.Create();
        }
        return MachineKeySection.ByteArrayToHexString(algorithm.ComputeHash(Encoding.UTF8.GetBytes(password)), 0);
    }
    

    下面是您的更新代码:

        encoding.GetBytes("asdf");
    
        var hashedBytes = MD5.Create().ComputeHash(bytes);
        var password = Encoding.UTF8.GetString(hashedBytes);
    
        2
  •  6
  •   Sentient    13 年前

    在谷歌搜索之后,我修改了@pieter的代码,使其独立于system.web。

    return string.Join("",
      new MD5CryptoServiceProvider().ComputeHash(
        new MemoryStream(Encoding.UTF8.GetBytes(password))).Select(x => x.ToString("X2")));
    
        3
  •  4
  •   OmarElsherif    12 年前

    此答案源自您的答案:

    .NET中的此方法与PHP中的sha1等效:

    string sha1Hash(string password)
    {
        return string.Join("", SHA1CryptoServiceProvider.Create().ComputeHash(Encoding.UTF8.GetBytes(password)).Select(x => x.ToString("X2"))).ToLower();
    }
    
        4
  •  3
  •   Pieter van Ginkel    14 年前

    以下是使用该方法创建密码的实际代码:

    System.Web.Configuration.MachineKeySection.ByteArrayToHexString(
        System.Security.Cryptography.MD5.Create().ComputeHash(
            Encoding.UTF8.GetBytes(password)
        ), 0
    );
    
        5
  •  2
  •   user2389005    10 年前
    public static string sha1Hash(string password)
        {
               return string.Join("", MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(password)).Select(s => s.ToString("x2"))).ToLower();
    
        }