如何在.Net Core中生成HMAC-SHA256? [英] How to generate HMAC-SHA256 in .Net Core?

查看:354
本文介绍了如何在.Net Core中生成HMAC-SHA256?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此页面为某些文本生成一些测试HMAC-SHA256哈希:

I am using this page to generate some test HMAC-SHA256 hashes for some texts:

https://www.liavaag.org/English/SHA-Generator/HMAC/

但是,当我尝试在此.NET Core项目中的MSDN指南,我没有得到相同的结果.有人可以向我解释如何获得与我在C#代码中从上一页获得的结果相同的结果吗?

However, when I try to use the approach in this MSDN guide in my .Net Core project, I do not get the same results. Could some one explain to me how to get identical results to those I get from the previous web page in my C# code?

这是我的代码:

// My own GetHash method usage:
var hashed = PasswordHelper.GetHash("Test", Encoding.UTF8.GetBytes("123"));

public static string GetHash(string password, byte[] salt)
{
    // derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations)
    string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
        password: password,
        salt: salt,
        prf: KeyDerivationPrf.HMACSHA256,
        iterationCount: 10000,
        numBytesRequested: 256 / 8));
    return hashed;
}

推荐答案

使用以下方法:

public static String GetHash(String text, String key)
{
    // change according to your needs, an UTF8Encoding
    // could be more suitable in certain situations
    ASCIIEncoding encoding = new ASCIIEncoding();

    Byte[] textBytes = encoding.GetBytes(text);
    Byte[] keyBytes = encoding.GetBytes(key);

    Byte[] hashBytes;

    using (HMACSHA256 hash = new HMACSHA256(keyBytes))
        hashBytes = hash.ComputeHash(textBytes);

    return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
}

您将获得与您提供的网站相同的结果:

you will get the same result as the site you provided:

Console.WriteLine(GetHash("qwerty","123456"));
// 3364ad93c083dc76d7976b875912442615cc6f7e3ce727b2316173800ca32b3a

证明:

实际上,您所使用的代码基于

Actually, the code you are using, which is based on this tutorial and on KeyDerivation.Pbkdf2, is producing different results because it uses a much more complex parametrization and another encoding. But despite the results being different, you should REALLY use the approach provided by the example, and stick on the UTF8 encoding.

这篇关于如何在.Net Core中生成HMAC-SHA256?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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