SHA256 base 64 hash generation in SQL Server

穿精又带淫゛_ 提交于 2019-12-01 00:06:30

First, the generator link you provided outputs the base64 representation in not exactly correct format. Namely, it omits the padding sequence. Though theoretically optional, padding is mandatory in MS SQL Server (tested on 2012 and 2016 versions).

With this in mind, the following code gives you what you need:

declare @s varchar(max), @hb varbinary(128), @h64 varchar(128);

select @s = '2016-01-012016-12-31123456789012000EUR';

set @hb = hashbytes('sha2_256', @s);
set @h64 = cast(N'' as xml).value('xs:base64Binary(sql:variable("@hb"))', 'varchar(128)');

select @hb as [BinaryHash], @h64 as [64Hash];

Apart from the aforementioned padding, there is another caveat for you to look for. Make sure that the input string is always of the same type, that is, either always varchar or always nvarchar. If some of your hashes will be calculated from ASCII strings and some from UTF-16, results will be completely different. Depending on which languages are used in your system, it might make sense to always convert the plain text to nvarchar before hashing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!