且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 .Net Core 中生成 HMAC-SHA256?

更新时间:2023-09-18 20:05:16

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.