代码之家  ›  专栏  ›  技术社区  ›  Mohammed Noureldin Reedwanul Islam

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

  •  15
  • Mohammed Noureldin Reedwanul Islam  · 技术社区  · 8 年前

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

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

    然而,当我尝试在 this MSDN guide 在我的。Net核心项目,我没有得到同样的结果。有人能给我解释一下如何得到与我在C代码中的上一个网页相同的结果吗?

    这是我的代码:

    // 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;
    }
    
    1 回复  |  直到 8 年前
        1
  •  44
  •   Tommaso Belluzzo    8 年前

    使用以下方法:

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

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

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

    证明:

    Proof

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