繁体   English   中英

用两个参数散列“SHA256”

[英]hashing “SHA256” with two parameters

我必须转换哈希字符串的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. 字符串值:它是crypt的字符串
  2. 字符串键:这是另一个关键

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

请问,我怎样才能在c#中编写这个函数,或者有没有人可以向我解释逻辑?

谢谢

您可以使用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;
    }

这不是简单的SHA256,这是HMACSHA256,并且已经在.Net中有一个类。 HMACSHA256

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM