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

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

问题描述

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

实际上,您使用的代码基于 本教程KeyDerivation.Pbkdf2 会产生不同的结果,因为它使用了更复杂的参数化和另一种编码.但是尽管结果不同,您应该真正使用示例提供的方法,并坚持使用 UTF8 编码.

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

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

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?

Here is my 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;
}

解决方案

Using the following approach:

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

Proof:

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天全站免登陆