首页 > 解决方案 > 如何在 USQL 中对字符串进行 SHA2 哈希处理

问题描述

我正在尝试为 USQL 中的字符串列运行单向哈希。有没有办法做到这一点?大多数在线找到的 C# 示例都需要多行代码——这在没有代码隐藏或编译 C# 程序集的 USQL 中很棘手。

标签: hashazure-data-lakeu-sql

解决方案


选项 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

推荐阅读