0

Why in SQL Server does the Hashbytes command return different responses in the following codes?

Declare @Pass nvarchar
set @Pass='SampleHash'
Select HASHBYTES('MD5',@Pass)
Select HASHBYTES('MD5','SampleHash')

---------------------------------------
0x6F0AC8C187CEDB835A9BA373603BDA3F

0xC205AF5CE2048FF5C8C9A5B5ABDAF64E
---------------------------------------
LordWilmore
  • 2,829
  • 2
  • 25
  • 30
Kh.N.
  • 1
  • 1
  • nvarchar is unicode, try with varchar and see the result. – Jacob H Jan 26 '18 at 14:02
  • You declared @Pass to be a single unicode character. And your literal is an ascii string of 10 characters. Jacob posted the correct version without spelling out the biggest mistake - a single character string. – SMor Jan 26 '18 at 14:27
  • @SMor Yeah I changed the type automatically without even thinking because declaring any character type in sql without a length gives me the creeps. Edited to include that information. – Jacob H Jan 26 '18 at 14:29

1 Answers1

2

By declaring your string as unicode you will get the same HASHBYTES result:

Declare @Pass nvarchar(10)
set @Pass='SampleHash'
Select HASHBYTES('MD5',@Pass)
Select HASHBYTES('MD5',N'SampleHash')

0xB8F6457C129AEBCBB0D2E3097336ED1C

Or by using varchar instead of nvarchar:

Declare @Pass varchar(10)
set @Pass='SampleHash'
Select HASHBYTES('MD5',@Pass)
Select HASHBYTES('MD5','SampleHash')

0xC205AF5CE2048FF5C8C9A5B5ABDAF64E

Edit: Note that I have also explicitly declared the lengths of the string values as nvarchar(10) or varchar(10) to match the length of the string SampleHash.

Jacob H
  • 2,455
  • 1
  • 12
  • 29