【问题标题】:hashing "SHA256" with two parameters使用两个参数散列“SHA256”
【发布时间】:2013-06-26 17:01:30
【问题描述】:

我必须转换一个对字符串进行哈希处理的 JAVA 函数。

这是一个函数:

private static String hmacSha256(String value, String key) throws NoSuchAlgorithmException, InvalidKeyException {
byte[] keyBytes = key.getBytes();           
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(value.getBytes());
return String.format("%0" + (rawHmac.length << 1) + "x", new BigInteger(1, rawHmac));
}

我的疑问是:这个函数有2个参数:

  1. 字符串值:要加密的字符串
  2. 字符串键:这是另一个键

我已经用过Sha256,但我总是只用一个参数(一个字符串加密)

请问,我该如何用 c# 编写这个函数,或者有谁能给我解释一下逻辑吗?

谢谢

【问题讨论】:

标签: c# java sha256


【解决方案1】:

您可以使用HMACSHA256 类使其工作:

    private static string ComputeHash(string key, string value)
    {
        var byteKey = Encoding.UTF8.GetBytes(key);
        string hashString;

        using (var hmac = new HMACSHA256(byteKey))
        {
            var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(value));
            hashString = Convert.ToBase64String(hash);
        }

        return hashString;
    }

【讨论】:

    【解决方案2】:

    这不是普通的 SHA256,这是 HMACSHA256,.Net 中已经有一个类。 HMACSHA256

    【讨论】:

      猜你喜欢
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 2015-01-23
      • 2022-01-23
      • 2015-12-14
      • 2019-10-11
      • 2019-10-04
      相关资源
      最近更新 更多