Bee*_*jee 8 c# t-sql sql-server hash encoding
我使用散列密码和salt(用户名).
问题是c#的散列值不等于我通过TSQL脚本添加到数据库的初始值.
TSQL:
UPDATE [Users]
SET Password = HASHBYTES('SHA2_256', 'test123'+UPPER([UserName]))
GO;
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
我想这与编码有关.但我不知道如何解决这个问题.
UserName是varchar(50)
DB是现有的,因此更改varchar并不容易.
我已经尝试过:
UPDATE [Users]
SET Password = HASHBYTES('SHA2_256', N'test123'+UPPER([UserName]))
GO;
Run Code Online (Sandbox Code Playgroud)
如果您的SQL Server数据库配置为使用SQL_Latin1_General_CP1_CI_AS的默认排序规则,那么在您的C#代码中,使用代码页1252将字符转换为字节.因此,相当于
HASHBYTES('SHA2_256', 'test123' + UPPER([UserName]))
Run Code Online (Sandbox Code Playgroud)
是
byte[] data = Encoding.GetEncoding(1252).GetBytes("test123" + userName.ToUpper());
var sha = new SHA256Managed();
byte[] hash = sha.ComputeHash(data);
Run Code Online (Sandbox Code Playgroud)
散列仅对字节有效,而不对字符有效。你在做什么Hash(StringToBytes(str))。您的StringToBytes步骤不同。在SQL中,您使用ANSI varchar字符串,在C#UTF-16字符串中。确定您要使用的那个。我建议使用Unicode(nvarchar)。
在努力使之工作之后,下面是我终于开始工作的示例:
public string Hash(string input)
{
using (SHA256 hasher = SHA256.Create())
{
// Convert the input string to a byte array and compute the hash.
byte[] data = hasher.ComputeHash(Encoding.Unicode.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("X2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
TSQL
declare @input as nvarchar(max) = 'Test';
select @input;
declare @hash as varbinary(max) = HASHBYTES('SHA2_256', @input );
select @hash;
declare @result as nvarchar(max) = CONVERT(NVARCHAR(MAX), @hash, 2);
select @result;
Run Code Online (Sandbox Code Playgroud)
这些将产生相同的结果。
请注意,这使用的是nvarchar数据类型,而不是varchar。
| 归档时间: |
|
| 查看次数: |
4879 次 |
| 最近记录: |