【问题标题】:How to SHA2 hash a string in USQL如何在 SQL 中对字符串进行 SHA2 哈希处理
【发布时间】:2018-11-08 11:55:00
【问题描述】:

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

【问题讨论】:

  • 我希望这不是密码。
  • 不。不是为了密码! :)

标签: hash azure-data-lake u-sql


【解决方案1】:

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

【讨论】:

【解决方案2】:

实际上我建议您使用最近添加的“命名 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

【讨论】:

  • 我将此纳入我的答案。好东西,谢谢。
  • 酷!您还可以将这些变量打包成一个 U-SQL 包以供重复使用,并在需要时导入它们。
  • 看到了,但还没有检查出来。有兴趣尝试一下。
  • 这个性能对我的用例来说似乎很好,但我很好奇是否有任何方法可以在内联函数的上下文之外运行“MD5.Create()”,这样 MD5 对象就不会t 必须在每一行上重新创建?或者 USQL 会定位这种冗余并自动优化?
  • 很高兴知道。我已经更新了我的答案以在脚本顶部声明对象。这似乎提供了轻微的性能提升。
猜你喜欢
  • 2011-04-25
  • 1970-01-01
  • 2021-09-19
  • 2011-08-24
  • 2014-05-13
  • 1970-01-01
  • 1970-01-01
  • 2017-01-15
  • 1970-01-01
相关资源
最近更新 更多