Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在.Net Core中生成HMAC-SHA256?_C#_Hash_Asp.net Core_.net Core_Hmac - Fatal编程技术网

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

C# 如何在.Net Core中生成HMAC-SHA256?,c#,hash,asp.net-core,.net-core,hmac,C#,Hash,Asp.net Core,.net Core,Hmac,我正在使用此页面为一些文本生成一些测试HMAC-SHA256哈希: 然而,当我尝试在我的.Net核心项目中使用这种方法时,我并没有得到相同的结果。有人能给我解释一下如何得到与我在C#代码中的上一个网页相同的结果吗 这是我的密码: // My own GetHash method usage: var hashed = PasswordHelper.GetHash("Test", Encoding.UTF8.GetBytes("123")); public static string GetH

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

然而,当我尝试在我的.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;
}

采用以下方法:

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
证明:

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