【问题标题】:How can I manually check passwords hashed with SQL Server PWDENCRYPT in C#如何在 C# 中手动检查使用 SQL Server PWDENCRYPT 散列的密码
【发布时间】:2017-05-09 20:09:46
【问题描述】:

我有一堆旧密码哈希是在 SQL Server 中使用 PWDENCRYPT 完成的。我现在想在我的 C# 应用程序中验证这些哈希(如果密码匹配,随后将更新),而不将实际密码发送到 SQL Server。如何做到这一点?

【问题讨论】:

    标签: sql-server security password-hash


    【解决方案1】:

    按照此答案 (https://stackoverflow.com/a/18154134/545430) 中的建议,您可以编写类似的代码来检查在 SQL Server 2008 上使用 PWDENCRYPT 加密的密码。

    SqlConnection conn = new SqlConnection(<your connection string>);
    conn.Open();
    SqlCommand cmd = new SqlCommand(<select hash field>, conn);
    SqlDataReader reader = cmd.ExecuteReader();
    byte[] pwHash = new byte[20];
    byte[] dbHash = new byte[26];
    reader.Read();
    reader.GetBytes(0, 0, dbHash, 0, 26);
    int header = BitConverter.ToChar(dbHash, 0);
    
    if (header == 1) //SHA1 encryption in Server 2008
    {
        byte[] salt = new byte[4];
        Buffer.BlockCopy(dbHash, 2, salt, 0, 4);
        Buffer.BlockCopy(dbHash, 6, pwHash, 0, 20);
    
        HashAlgorithm cryptoThing = SHA1.Create();
        byte[] test = cryptoThing.ComputeHash(Encoding.Unicode.GetBytes("mypw" + Encoding.Unicode.GetString(salt)));
        if (pwHash.SequenceEqual(test))
        {
            //Password is good
        }
    }
    

    在 2012 年或之后完成的密码使用 SHA2-256,并且标头值为 2。此代码也可以轻松更新以处理该问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 2017-11-16
      • 2021-05-19
      相关资源
      最近更新 更多