如何在SQL Server 2016中生成SHA-3(256)哈希?
HASHBYTES似乎仅上升到SHA-2(256)或SHA-2(512)。
Microsoft BOL内置于任何地方,不会给我带来温暖和模糊。
-- SHA2-256
DECLARE @HashThis nvarchar(32);
SET @HashThis = CONVERT(nvarchar(32),'123456');
SELECT HASHBYTES('SHA2_256', @HashThis);
-- Output: 0xEC278A38901287B2771A13739520384D43E4B078F78AFFE702DEF108774CCE24
-- SHA3-256 (KECCAK)
DECLARE @HashThis nvarchar(32);
SET @HashThis = CONVERT(nvarchar(32),'123456');
SELECT HASHBYTES('SHA3_256', @HashThis);
-- Output: NULL
您可以通过SQL Server CLR
集成实现SHA-3 256哈希
GitHub上有一个项目已经为您完成了大部分工作,您可以轻松地为其添加SHA3支持。
https://github.com/sedenardi/sql-hashing-clr
纯dotnet核心无法实现SHA3-256哈希。我建议您使用具有SHA3-256支持的BouncyCastle库(https://www.bouncycastle.org/csharp/index.html)。有一个nuget库程序包,它是BouncyCastle的包装,可以使SHA3-256哈希比较容易实现。https://www.nuget.org/packages/SHA3.Net/。您需要使用此软件包并进行更新HashUtil.cs
先决条件:构建CLR .dll
using System;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Security.Cryptography;
-- include NugetPackage to help with SHA-3 hashing
public class HashUtil
{
[SqlFunction(IsDeterministic = true)]
public static SqlBinary GetHash(SqlString algorithm, SqlBytes src)
{
if (src.IsNull)
return null;
switch (algorithm.Value.ToUpperInvariant())
{
case "MD5":
return new SqlBinary(MD5.Create().ComputeHash(src.Stream));
case "SHA1":
return new SqlBinary(SHA1.Create().ComputeHash(src.Stream));
case "SHA2_256":
return new SqlBinary(SHA256.Create().ComputeHash(src.Stream));
case "SHA2_512":
return new SqlBinary(SHA512.Create().ComputeHash(src.Stream));
-- add SHA3-256
default:
throw new ArgumentException("HashType", "Unrecognized hashtype: " + algorithm.Value);
}
}
}
将CLR .dll部署到SQL Server
作为参考,这里是有关如何部署CLR .dll的Microsoft文档。
将功能部署到SQL Server
CREATE FUNCTION dbo.GetHashHybrid(@algorithm NVARCHAR(4000),@input VARBINARY(MAX))
RETURNS VARBINARY(8000) WITH SCHEMABINDING
AS
BEGIN
RETURN (
SELECT dbo.GetHash(@algorithm,@input)
)
END
呼叫dbo.GetHash
DECLARE @INPUT VARCHAR(MAX);
SELECT @INPUT = REPLICATE(CAST('test1' AS VARCHAR(MAX)),2000);
SELECT dbo.GetHash('MD5',CONVERT(VARBINARY(MAX),@INPUT));
此示例显示了MD5散列,但演示了如何使用CLR创建散列功能的概念,当前SQL Server尚不支持这种功能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句