HASHBYTES encrytion length and quering issue

Priya Jha 871 Reputation points
2021-02-17T13:04:45.787+00:00

I am running the following query to encrypt certain value:

declare @peoplekey int
set @peoplekey = 500

select HASHBYTES('SHA2_256',cast(@peoplekey as varbinary(2000)))

The output is : 0xDC28C75DEDB09C0B0510B97BC59F879E7741BA2A396CBAA430623ED4CEAA0EF6

But when i am explicitly trying to get the length of the query output vs the actual output, i am getting two different values:

select len(HASHBYTES('SHA2_256',cast(@peoplekey as varbinary(2000))))

select len('0xDC28C75DEDB09C0B0510B97BC59F879E7741BA2A396CBAA430623ED4CEAA0EF6')

69076-length.png

Why lengths of both these statements are different?

Also, i have inserted the above encrypted value in a table using this statement:
insert into #test
select @peoplekey,HASHBYTES('SHA2_256',convert(varbinary,@peoplekey))

And the data is getting inserted correctly. But when i am trying to filter data using this varbinary value i get 0 rows in the output

select * from #test where c2 = '0xDC28C75DEDB09C0B0510B97BC59F879E7741BA2A396CBAA430623ED4CEAA0EF6'

How can we query varbinary data present in the table?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,133 questions
0 comments No comments
{count} votes

Accepted answer
  1. Sean Gallardy - MSFT 1,886 Reputation points Microsoft Employee
    2021-02-17T13:36:53.217+00:00

    [...] but when i am explicitly trying to get the length of the query output vs the actual output, i am getting two different values:

    That's because you are treating the binary value as a string value, so it will be double the size (UCS2) + the size of "0x" that is prepended. Consider the following in your situation:

    declare @peoplekey int
    set @peoplekey = 500
    
    select len(HASHBYTES('SHA2_256',cast(@peoplekey as varbinary(2000))))
    select len('0xDC28C75DEDB09C0B0510B97BC59F879E7741BA2A396CBAA430623ED4CEAA0EF6')
    select len(0xDC28C75DEDB09C0B0510B97BC59F879E7741BA2A396CBAA430623ED4CEAA0EF6)
    

    Notice on the last one (I added, not in your original) I treat the value as a binary, not a string.

    2 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.