Reading binary file from table column to byte array []

I use PBKDF2 in my application to store user passwords. My Users table has a Salt and Password column which is defined as follows:

 // 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 get this salt and password. Since they are byte [] arrays, I store them in my table as varbinary(MAX) . Now I need to get them to compare with the password entered by the user. How would I do this 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 sure that this is wrong. Other methods in Reader have only one parameter, which is the index of the column to retrieve.

+6
source share
2 answers

Clicking on it directly byte[] 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 } } } } 
+7
source

I'm not sure why you think the code you wrote is incorrect (please explain). But specifically for the error:
Note that GetBytes returns a long non-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);

+2
source

Source: https://habr.com/ru/post/1445349/


All Articles