我正在尝试在SQL Server 2008 R2中存储散列密码,但是当我将存储的版本与原始版本进行比较时,它们不匹配。
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)
{
}
SQL Server表包含以下列:
TABLE [dbo].[USERS]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[SALT] [nvarchar](50) NOT NULL,
[PASSWORD] [nvarchar](50) NOT NULL,
.........
)
这是我的数据库访问代码:
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);
}
}
这是我的User
对象
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; }
所以我认为SQL Server表中的列类型必须错误。
答案 0 :(得分:2)
如果你想要密码哈希匹配你需要使用数据库中保存的盐而不是创建一个新的