使用 Sha256 散列字符串 [英] Hashing a string with Sha256

查看:27
本文介绍了使用 Sha256 散列字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 SHA256 对字符串进行哈希处理,我正在使用以下代码:

I try to hash a string using SHA256, I'm using the following code:

using System;
using System.Security.Cryptography;
using System.Text;
 public class Hash
    {
    public static string getHashSha256(string text)
    {
        byte[] bytes = Encoding.Unicode.GetBytes(text);
        SHA256Managed hashstring = new SHA256Managed();
        byte[] hash = hashstring.ComputeHash(bytes);
        string hashString = string.Empty;
        foreach (byte x in hash)
        {
            hashString += String.Format("{0:x2}", x);
        }
        return hashString;
    }
}

但是,与我的朋友 php 以及在线生成器(例如 此生成器)

However, this code gives significantly different results compared to my friends php, as well as online generators (such as This generator)

有谁知道错误是什么?不同的基础?

Does anyone know what the error is? Different bases?

推荐答案

Encoding.Unicode 是 Microsoft 对 UTF-16(一种双宽编码,由于历史原因在 Windows 世界中使用)的误导性名称但没有被其他人使用).http://msdn.microsoft.com/en-us/library/system.text.encoding.unicode.aspx

Encoding.Unicode is Microsoft's misleading name for UTF-16 (a double-wide encoding, used in the Windows world for historical reasons but not used by anyone else). http://msdn.microsoft.com/en-us/library/system.text.encoding.unicode.aspx

如果你检查你的 bytes 数组,你会看到每第二个字节都是 0x00(因为双宽编码).

If you inspect your bytes array, you'll see that every second byte is 0x00 (because of the double-wide encoding).

您应该改用 Encoding.UTF8.GetBytes.

此外,根据您是否将终止 '' 字节视为正在散列的数据的一部分,您将看到不同的结果.散列两个字节 "Hi" 将给出与散列 三个 字节 "Hi" 不同的结果.你必须决定你想做什么.(想必你想做你朋友的 PHP 代码正在做的任何一个.)

But also, you will see different results depending on whether or not you consider the terminating '' byte to be part of the data you're hashing. Hashing the two bytes "Hi" will give a different result from hashing the three bytes "Hi". You'll have to decide which you want to do. (Presumably you want to do whichever one your friend's PHP code is doing.)

对于 ASCII 文本,Encoding.UTF8 绝对适合.如果您的目标是与您朋友的代码完美兼容,即使是在非 ASCII 输入上,您最好尝试一些带有非 ASCII 字符的测试用例,例如 é 看看你的结果是否仍然匹配.如果没有,你就必须弄清楚你的朋友真正使用的是什么编码;它可能是在 Unicode 发明之前曾经流行的 8 位代码页"之一.(同样,我认为 Windows 是任何人仍然需要担心代码页"的主要原因.)

For ASCII text, Encoding.UTF8 will definitely be suitable. If you're aiming for perfect compatibility with your friend's code, even on non-ASCII inputs, you'd better try a few test cases with non-ASCII characters such as é and and see whether your results still match up. If not, you'll have to figure out what encoding your friend is really using; it might be one of the 8-bit "code pages" that used to be popular before the invention of Unicode. (Again, I think Windows is the main reason that anyone still needs to worry about "code pages".)

这篇关于使用 Sha256 散列字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆