【问题标题】:generating MD5 hash of a text with C#使用 C# 生成文本的 MD5 哈希
【发布时间】:2010-09-28 08:45:41
【问题描述】:

我了解 System.Security.Cryptography 在MD5.ComputeHash 中有一个 MD5 散列方法。但是,该方法接受并返回字节。我不明白如何使用字符串键和散列来使用这种方法。我尝试通过这样做来解决问题,

var hash = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(@"text".ToCharArray()));
foreach(byte h in hash)
{
    Console.Write((char)h);
}

但是,结果输出是乱码字符串。作为对比,在this website中,输入“text”会得到“1cb251ec0d568de6a929b520c4aed8d1”

【问题讨论】:

  • oops 忽略了哈希通常使用十六进制格式化。有兴趣的请看下面我的回答:

标签: hash cryptography md5


【解决方案1】:

编写此代码将得到与网站相同的结果:

var hash = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(@"text".ToCharArray()));
foreach(byte h in hash)
{
     Console.Write(h.ToString("x2"));
}

诀窍是将每个字节打印为 2 个十六进制数字(因此 x2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 2011-07-26
    • 2015-08-14
    • 1970-01-01
    • 2020-12-08
    • 2017-05-24
    相关资源
    最近更新 更多