I am trying to store a hashed password in SQL Server 2008 R2 but when I compare the stored version with original they do not match.
string password = "12345";
User user = new User();
user.USERNAME = "JohnDoe";
using (var rngCsp = new RNGCryptoServiceProvider())
{
byte[] salt = new byte[32];
rngCsp.GetBytes(salt);
user.SALT = UTF8Encoding.UTF8.GetString(salt);
}
using (SHA256CryptoServiceProvider sha = new SHA256CryptoServiceProvider())
{
user.PASSWORD = UTF32Encoding.UTF8.GetString(sha.ComputeHash(UTF8Encoding.UTF8.GetBytes(password + user.SALT)));
}
//store the user on db
db.UserUpdate(user);
// now get the db values that have been saved and compare with original
var userOnDB = db.UsersGet(user.USERNAME);
var passwordOnDb = userOnDB.PASSWORD;
//this returns false
if (passwordOnDb == user.PASSWORD)
{
}
The SQL Server table has the columns:
TABLE [dbo].[USERS]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[SALT] [nvarchar](50) NOT NULL,
[PASSWORD] [nvarchar](50) NOT NULL,
.........
)
This is my DB access code:
public USER UsersGet(string userName)
{
using (MyEntities ctx = new MyEntities())
{
return ctx.USERS.Where(a => a.USERNAME == userName).FirstOrDefault();
}
}
public void UserUpdate(USER user)
{
try
{
using (MyEntities ctx = new MyEntities())
{
if (controller.ID == 0)
{
ctx.Entry(user).State = System.Data.Entity.EntityState.Added;
}
else
{
ctx.Entry(user).State = System.Data.Entity.EntityState.Modified;
}
ctx.SaveChanges();
}
}
catch (Exception ex)
{
throw new Exception(ex.InnerException.InnerException.Message);
}
}
Here is my User
object
public int ID { get; set; }
public string FIRSTNAME { get; set; }
public string LASTNAME { get; set; }
public string ADDRESS1 { get; set; }
public string ADDRESS2 { get; set; }
public string ADDRESS3 { get; set; }
public string TOWN { get; set; }
public string POCODE { get; set; }
public string MOBILE { get; set; }
public string COMMENTS { get; set; }
public bool ACTIVE { get; set; }
public string NIC { get; set; }
public string LANDLINE { get; set; }
public string USERNAME { get; set; }
public string EMAIL { get; set; }
public string SALT { get; set; }
public string PASSWORD { get; set; }
So I thought I must have wrong column types in SQL Server table.
If you want the password hash to match you need to use the salt saved in the database not create a new one