C#哈希SHA256Managed不等于TSQL SHA2_256 [英] C# Hash SHA256Managed is not equal to TSQL SHA2_256
问题描述
我正在使用带有盐(用户名)的哈希密码.
I am using hashed passwords with a salt (the username).
问题是c#的哈希值不等于我通过TSQL脚本添加到数据库中的初始值.
Problem is that the hashed values of c# are not equal to the initial values I add to the database by a TSQL Script.
TSQL:
UPDATE [Users]
SET Password = HASHBYTES('SHA2_256', 'test123'+UPPER([UserName]))
GO;
C#:
var passBytes = new UnicodeEncoding().GetBytes(pass);
var saltBytes = new UnicodeEncoding().GetBytes(userName.ToUpper());
var dataToHash = new byte[passBytes.Length + saltBytes.Length];
Array.Copy(passBytes, dataToHash, passBytes.Length);
Array.Copy(saltBytes, dataToHash, saltBytes.Length);
var sha = new SHA256Managed();
return sha.ComputeHash(dataToHash);
我想这与编码有关. 但是我不知道如何解决这个问题.
I guess it has something to do with the encoding. But i have no idea how to fix this.
用户名是varchar(50)
UserName is varchar(50)
数据库是现有数据库,因此更改varchar并不容易.
我已经尝试过:
UPDATE [Users]
SET Password = HASHBYTES('SHA2_256', N'test123'+UPPER([UserName]))
GO;
推荐答案
如果将SQL Server数据库配置为使用SQL_Latin1_General_CP1_CI_AS的默认排序规则,则在C#代码中,使用代码页1252将字符转换为字节.因此,等价于
If your SQL Server database is configured to use the default collation of SQL_Latin1_General_CP1_CI_AS, then in your C# code, use code page 1252 to convert characters to bytes. Thus, the equivalent of
HASHBYTES('SHA2_256', 'test123' + UPPER([UserName]))
是
byte[] data = Encoding.GetEncoding(1252).GetBytes("test123" + userName.ToUpper());
var sha = new SHA256Managed();
byte[] hash = sha.ComputeHash(data);
这篇关于C#哈希SHA256Managed不等于TSQL SHA2_256的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!