0

基本上,我从访问数据库中获取保存的哈希(转换为base64)并将其与另一个进行比较(在将其转换回来之后),如果它们匹配,则应返回true,但由于某种原因,它返回false。数据库中有数据。我认为当哈希从base64转换回来时会出现问题。谁能看到我做错了什么?

private static bool MatchSHA(byte[] p1, byte[] p2)
    {
        bool result = false;
        if (p1 != null && p2 != null)
        {
            if (p1.Length == p2.Length)
            {
                result = true;
                for (int i = 0; i < p1.Length; i++)
                {
                    if (p1[i] != p2[i])
                    {
                        result = false;
                        break;
                    }
                }
            }
        }
        return result;
    }


private static byte[] GetSHA(string userID, string password)
    {
        SHA256CryptoServiceProvider sha = new SHA256CryptoServiceProvider();
        return sha.ComputeHash(System.Text.Encoding.ASCII.GetBytes(userID + password));
    }
public void RunTest()
    {
        string userId = "test";
        string password = "Password";
        string enteredPassword = "Password";
        var hashedPassword = GetSHA(userId, password);
        string encodedPassword = Convert.ToBase64String(hashedPassword);
        try
        {
            string connString = (@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=|DataDirectory|Password.accdb");
            OleDbConnection conn = new OleDbConnection(connString);
            conn.Open();
            OleDbCommand cmd = conn.CreateCommand();
            cmd.CommandText = @"SELECT * FROM [Users] WHERE [UserId] = @UserId";
            cmd.Parameters.AddWithValue("@UserId", userId);
            OleDbDataReader dbReader = cmd.ExecuteReader();
            while (dbReader.Read())
            {
               var compareHash = Convert.FromBase64String(dbReader["Password"].ToString());
               errorLabel.Text = "Hash from DB: " + dbReader["Password"].ToString();

                 if (MatchSHA(compareHash, GetSHA(userId, enteredPassword)))
                 {
                     loginLabel.Text = "EnteredPassword. True";
                 }
                 else
                 {
                     loginLabel.Text = "EnteredPassword. False";
                 }

            }
            conn.Close();

        }
        catch (OleDbException obe)
        {
            errorLabel.Text = obe.ToString();
        }
    }
4

0 回答 0