首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在.Net内核中生成HMAC-SHA256?

如何在.Net内核中生成HMAC-SHA256?
EN

Stack Overflow用户
提问于 2017-12-07 10:36:29
回答 1查看 19.5K关注 0票数 12

我正在使用这个页面为一些文本生成一些测试HMAC-SHA256散列:

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

但是,当我尝试在我的.Net核心项目中使用this MSDN guide中的方法时,我得不到相同的结果。有人能给我解释一下如何在我的C#代码中获得与上一个网页相同的结果吗?

下面是我的代码:

代码语言:javascript
复制
// 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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-07 10:50:12

使用以下方法:

代码语言:javascript
复制
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();
}

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

代码语言:javascript
复制
Console.WriteLine(GetHash("qwerty","123456"));
// 3364ad93c083dc76d7976b875912442615cc6f7e3ce727b2316173800ca32b3a

证明:

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

票数 38
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47686677

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档