Question

I'm doing some encryption tasks in C# and ran into an issue I can't quite figure out. I sometimes get very complex salted hash strings for users passwords and these strings, for some reason, aren't getting stored in the database correctly.

I'm using an 8-byte salt randomly generated from the RNGCryptoServiceProvider class. I am using the SHA256Managed class as my HashAlgorithm. I'm getting the string to store from the bytes created via the ASCIIEncoding.Default.GetString() method. The column these values are being stored in is of type (NVARCHAR(50), NULL). I'm storing them using the SqlCommand class.

I can see the exact string fine when stepping through my code and using the immediate window. It seems like the problem is happening when I call cmd.ExecuteNonQuery(). Should I be doing it differently than below?

string query = @"UPDATE User SET password = @password WHERE id = @userID";

cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@password", encryptedPassword);
cmd.Parameters.AddWithValue("@userID", userID);

int rowsAffected = cmd.ExecuteNonQuery();

If you require any further information, let me know. I just don't wanna put too much on here about my exact algorithm or the results of it.

Thank you.

Was it helpful?

Solution

Try using Convert.ToBase64String() instead for encoding byte array into string. This should solve your problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top