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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
}
}
}
}
Method 2
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);
or
long bytesRead = Reader.GetBytes(0, 0, _Salt, 0, _Salt.Length);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0