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
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
}
}
}
}
I'm not sure why you think the code you wrote is wrong (please explain). But specifically for the error:
Notice that GetBytes returns a long
not a byte array.
So, you should use:
Reader.GetBytes(0, 0, _Salt, 0, _Salt.Length);
orlong bytesRead = Reader.GetBytes(0, 0, _Salt, 0, _Salt.Length);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With