hash - 如何在 USQL 中对字符串进行 SHA2 哈希处理
问题描述
我正在尝试为 USQL 中的字符串列运行单向哈希。有没有办法做到这一点?大多数在线找到的 C# 示例都需要多行代码——这在没有代码隐藏或编译 C# 程序集的 USQL 中很棘手。
解决方案
选项 1(内联公式):
下面的代码可用于在任何字符串上编译 SHA256 或 MD5,并且无需任何特殊依赖项且无需代码隐藏文件即可运行。
CREATE TABLE master.dbo.Test_MyEmail_Hashes AS
SELECT
cust.CustEmailAddr AS Email
, String.Concat(System.Security.Cryptography.SHA256.Create()
.ComputeHash(Encoding.UTF8.GetBytes(
cust.CustEmailAddr))
.Select(item => item.ToString("x2")))
AS Email_SHA2
, String.Concat(System.Security.Cryptography.MD5.Create()
.ComputeHash(Encoding.UTF8.GetBytes(
cust.CustEmailAddr))
.Select(item => item.ToString("x2")))
AS Email_MD5
FROM master.dbo.Customers AS cust
;
选项 2(使用 Lambda 函数):(已更新)
感谢 @MichaelRys 提供的 USQL 现在支持 Lambda 函数的指针,并且可以如下所示进行清理:
// Generic get_hash() function
DECLARE @get_hash Func<string,System.Security.Cryptography.HashAlgorithm,string> =
(raw_value, hasher) => String.Concat(hasher.ComputeHash(Encoding.UTF8.GetBytes(raw_value)));
// Short-hand functions for MD5 and SHA256:
DECLARE @md5 = System.Security.Cryptography.MD5.Create();
DECLARE @get_md5 Func<string,string> =
(raw_value) => @get_hash(raw_value, @md5);
DECLARE @sha256 = System.Security.Cryptography.SHA256.Create();
DECLARE @get_sha256 Func<string,string> =
(raw_value) => @get_hash(raw_value, @sha256);
// Core query:
CREATE TABLE master.dbo.Test_MyEmail_Hashes AS
SELECT
cust.CustEmailAddr AS Email
, @get_sha256(cust.CustEmailAddr) AS Email_SHA2
, @get_md5(cust.CustEmailAddr) AS Email_MD5
FROM master.dbo.Customers AS cust
推荐阅读
- angular - 未涵盖声纳覆盖角度单元测试
- angular - 页面加载角度
- oracle - 使用 Oracle dbms_json 解析 json 数组的字符串
- multithreading - 多进程的进程间通信
- asp.net-core - 在 IIS 上的 ASP.NET Core 中为 Windows 身份验证配置 Kerberos
- git - 我不确定我的本地存储库是否处于正确的状态以推送到我的远程
- angular - 未拾取 ActivatedRoute 参数
- c# - 对“MarshalByRefObject”类型的引用声称它是在“System.Runtime”中定义的,但找不到
- aws-lambda - 失败:ValidationException:检测到 1 个验证错误:“tableName”处的值“[object Object]”未能满足约束
- jwt - 如何将用户添加到 Zoom 帐户的 JWT 密钥?