散列“SHA256"有两个参数 [英] hashing "SHA256" with two parameters

查看:82
本文介绍了散列“SHA256"有两个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I must convert a JAVA function that Hashing a string.

这是一个函数:

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));
}

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

My doubt is: this function take 2 parameters:

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

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

I already used the Sha256, but I always use it with only one parameter (one string to encrypt)

请问,我怎么用c#写这个函数,或者有谁能给我解释一下逻辑?

please, how can I wrote this function in c# or is there anyone who can explain to me the logical?

谢谢

推荐答案

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

You can use HMACSHA256 class to make it work:

    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"有两个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆