Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Hash SHA256Managed is not equal to TSQL SHA2_256

I am using hashed passwords with a salt (the username).

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.

UserName is varchar(50)

The DB is an existing one so changing the varchar will not be so easy.

I already tried:

UPDATE [Users]
SET Password = HASHBYTES('SHA2_256', N'test123'+UPPER([UserName]))
GO;
like image 801
Beejee Avatar asked Oct 06 '13 19:10

Beejee


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What does %= mean in C?

%= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A.

What is C full form?

Originally Answered: What is the full form of C ? C - Compiler . C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972.

How old is the letter C?

The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.


1 Answers

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]))

is

byte[] data = Encoding.GetEncoding(1252).GetBytes("test123" + userName.ToUpper());
var sha = new SHA256Managed();
byte[] hash = sha.ComputeHash(data);
like image 152
Michael Liu Avatar answered Sep 24 '22 18:09

Michael Liu