【问题标题】:Reading binary from table column into byte[] array将表列中的二进制文件读入 byte[] 数组
【发布时间】:2012-11-11 16:14:39
【问题描述】:

我在我的应用程序中使用 PBKDF2 来存储用户密码。在我的用户表中,我有一个 SaltPassword 列,其确定如下:

// Hash the users password using PBKDF2
var DeriveBytes = new Rfc2898DeriveBytes(_Password, 20);
byte[] _Salt = DeriveBytes.Salt;
byte[] _Key = DeriveBytes.GetBytes(20);  // _Key is put into the Password column

在我的登录页面上,我需要检索此盐和密码。因为它们是 byte[] 数组,所以我将它们作为 varbinary(MAX) 存储在我的表中。现在我需要检索它们以与用户输入的密码进行比较。我将如何使用SqlDataReader 做到这一点?目前我有这个:

cn.Open();
SqlCommand Command = new SqlCommand("SELECT Salt, Password FROM Users WHERE Email = @Email", cn);
Command.Parameters.Add("@Email", SqlDbType.NVarChar).Value = _Email;
SqlDataReader Reader = Command.ExecuteReader(CommandBehavior.CloseConnection);
Reader.Read();
if (Reader.HasRows)
{
    // This user exists, check their password with the one entered
    byte[] _Salt = Reader.GetBytes(0, 0, _Salt, 0, _Salt.Length);
}
else
{
    // No user with this email exists
    Feedback.Text = "No user with this email exists, check for typos or register";
}

但我知道这是错误的。 Reader 中的其他方法只有一个参数是要检索的列的索引。

【问题讨论】:

  • 你怎么知道它错了?因为您所做的正是所有其他相关问题正在做的事情。你确定你创建的字节数组适合varbyte
  • VS 抛出一个错误,说它不能将 long 转换为 byte[] for one,并且参数描述与我输入的不匹配,比如Salt._Length

标签: c# asp.net arrays sql-server


【解决方案1】:

到目前为止,将其直接转换为 byte[] 对我有用。

using (SqlConnection c = new SqlConnection("FOO"))
{
    c.Open();
    String sql = @"
        SELECT Salt, Password 
        FROM Users 
        WHERE (Email = @Email)";
    using (SqlCommand cmd = new SqlCommand(sql, c))
    {
        cmd.Parameters.Add("@Email", SqlDbType.NVarChar).Value = _Email;
        using (SqlDataReader d = cmd.ExecuteReader())
        {
            if (d.Read())
            {
                byte[] salt = (byte[])d["Salt"];
                byte[] pass = (byte[])d["Password"];

                //Do stuff with salt and pass
            }
            else
            {
                // NO User with email exists
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    我不确定您为什么认为您编写的代码是错误的(请解释)。但专门针对错误:
    请注意,GetBytes 返回的是 long,而不是字节数组。

    所以,你应该使用: Reader.GetBytes(0, 0, _Salt, 0, _Salt.Length);


    long bytesRead = Reader.GetBytes(0, 0, _Salt, 0, _Salt.Length);

    【讨论】:

    • 如果您查看该方法所需的参数,您会发现我的参数不正确,但我不知道该指定什么。而且我无法将其转换为 long,它必须以字节数组的形式返回,我的密码检查才能正常工作。
    • @JamesDawson 请阅读 GetBytes 函数的描述(我在我的回答中发布):从指定的列偏移量将字节流读取到缓冲区中,数组开始于给定的缓冲区偏移量。换句话说,在您的示例中,将列号 0 的字节流复制到 _Salt 变量中。这正是你所要求的。 (GetBytes 函数的返回值只是读取的字节数,因此它是long)。您是否按照我的建议更改了代码?成功了吗?
    猜你喜欢
    • 2011-05-14
    • 2011-12-24
    • 1970-01-01
    • 2019-05-14
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多