散列与SHA256字符串 [英] Hashing a string with Sha256

查看:197
本文介绍了散列与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,以及在线发生器(如该发电机

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

Does anyone know what the error is? Different bases?

推荐答案

Encoding.Unicode 是微软的误导名称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

如果您检查您的字节数组,你会看到每第二个字节是 0×00 (因为双宽编码)。

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

您应该使用 Encoding.UTF8.GetBytes 代替。

但同时,你会看到不同的结果取决于您是否不考虑终止'\0 字节是你要散列数据的一部分。哈希两个字节将给出不同的结果从哈希的的字节。你必须决定你想做的事情。 (想必你想做哪一个朋友的PHP代码做的。)

But also, you will see different results depending on whether or not you consider the terminating '\0' 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天全站免登陆