如何在SQL Server 2008 R2中存储哈希密码
本文关键字:存储 哈希 密码 R2 2008 SQL Server | 更新日期: 2023-09-27 18:21:04
我试图在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表中一定有错误的列类型。
如果你想让密码哈希匹配,你需要使用保存在数据库中的salt,而不是创建一个新的