从表列读二进制成byte []数组 [英] Reading binary from table column into byte[] array

查看:91
本文介绍了从表列读二进制成byte []数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用PBKDF2来存储用户的密码。在我的用户表,我是这样确定的密码列:

I'm using PBKDF2 in my application to store users passwords. In my Users table, I have a Salt and Password column which is determined like this:

// 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的?目前,我有这样的:

On my login page I need to retrieve this salt and password. Because they're byte[] arrays, I store them in my table as varbinary(MAX). Now I need to retrieve them to compare against the users entered password. How would I do that using SqlDataReader? At the moment I have this:

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";
}

但我知道一个事实,这是错误的。在阅读其他方法只有一个参数是列的索引检索。

But I know for a fact that it's wrong. Other methods in Reader have only one parameter being the index of the column to retrieve.

谢谢!

推荐答案

直接浇铸成字节[] 迄今已为我工作。

Casting it directly to a byte[] has worked for me so far.

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
            }
        }
    }
}

这篇关于从表列读二进制成byte []数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆