如何在 USQL 中对字符串进行 SHA2 哈希处理

How to SHA2 hash a string in USQL

我正在尝试 运行 USQL 中字符串列的单向散列。有没有办法内联执行此操作?在网上找到的大多数 C# 示例都需要多行代码 - 这在没有代码隐藏或编译的 C# 程序集的 USQL 中很棘手。

实际上,我建议您使用最近添加的 "named lambdas"(Func<> 类型变量)来使用多行 C# 示例。示例如下:https://github.com/Azure/AzureDataLake/blob/master/docs/Release_Notes/2018/2018_Spring/USQL_Release_Notes_2018_Spring.md#u-sql-adds-c-func-typed-variables-in-declare-statements-named-lambdas

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