How to generate HMAC-SHA256 in .Net Core?

前端 未结 1 1509
陌清茗
陌清茗 2021-02-14 07:46

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

1条回答
  •  难免孤独
    2021-02-14 08:13

    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.

    0 讨论(0)
提交回复
热议问题