[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 249
  • Last Modified:

SHA1 Hash creation returning different results in SQL Server

HI all,
If I create a HASH on SQL Server using two different methods and get two different results and I can't figure out why.  One is correct based on a similar function I am using in VB.net; so I know that the 2nd SQL function is correct, at least the result i'm accpecting.

'First Code (Not correct)
DECLARE @SomeValue nvarchar(50)
SELECT @SomeValue = 'ME@SomeValue'
SELECT HashBytes('SHA1', @SomeValue)
GO

'Result = 0x05B922B8F204CDA36731DC3078563D7E18D27052

'------------------------------------------------------------------------------
'2nd Code (Correct)
SELECT HashBytes('SHA1', 'ME@SomeValue')

'Result = 0xE45FD18F98479679C7B04122F4B7C6D3D6962463
0
Thunder724
Asked:
Thunder724
  • 2
  • 2
1 Solution
 
Russ SuterCommented:
In the first example you are passing a unicode string. In the second it's an ASCII string. If you modify your first example as follows you'll get the same result both times:

DECLARE @SomeValue varchar(50)
SELECT @SomeValue = 'ME@SomeValue'
SELECT HashBytes('SHA1', @SomeValue)

Open in new window


Alternately, if you modify your second example as follows you'll be passing a unicode string and you'll get the same response as the first example.

SELECT HashBytes('SHA1', N'ME@SomeValue')

Open in new window

0
 
Thunder724Author Commented:
Thanks but in the first example you are giving me it looks like the same code.
Am I not seeing something here?

thanks,
John.
0
 
Russ SuterCommented:
You declared the variable as "nvarchar(50)". I declared it as "varchar(50)". Note that I didn't include the "n" at the beginning. This specifies an ASCII string rather than a unicode string.
0
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
Thunder724, Russ Suter's right.
If you check it better you'll see that they are different data types.

In your example is a Nvarchar(50) and in his example it's a Varchar(50). That 'N' makes all the difference between being Unicode or not.
0
 
Thunder724Author Commented:
Oh yes.. Good grief that was driving me crazy.  I think I need new glasses.
Thanks very much.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now