Thursday, November 13, 2014

Working with SHA1 on SQL Server


There are times you might need to convert some information to MD5 on your SQL Server in HEX format. As it is for now there is no out of the box function to do it on SQL Server. But you can easily accomplish this task by using the following function:
create FUNCTION [dbo].[sha1]
(
        @value varchar(4000)
)
RETURNS varchar(40)
AS
BEGIN
  return
    case when @value is not null then
      SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('SHA1', @value)), 3, 40)
    else null end
END
GO

Testing it is quite straight forward. For example:
select dbo.sha1('123') 

And here is the output:
40bd001563085fc35165329ea1ff5c5ecbdbbeef


 

No comments:

Post a Comment