字符串SHA-512编码:C#和JAVA结果不同 [英] String SHA-512 Encoding: C# and JAVA result is different

查看:129
本文介绍了字符串SHA-512编码:C#和JAVA结果不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图比较sha512编码的两个不同的字符串。但是,结果是不同的。这可能是一个编码问题我的意思。我希望你能帮助我。

Im trying to compare two different string encoded by sha512. But, result is different. It can be an encode problem i mean. I hope you can help me.

这是我的Java代码:

This is my Java code:

    MessageDigest digest = java.security.MessageDigest.getInstance("SHA-512"); 
    digest.update(MyString.getBytes()); 
    byte messageDigest[] = digest.digest();

    // Create Hex String
    StringBuffer hexString = new StringBuffer();
    for (int i = 0; i < messageDigest.length; i++) {
        String h = Integer.toHexString(0xFF & messageDigest[i]);
        while (h.length() < 2)
            h = "0" + h;
        hexString.append(h);
    }
    return hexString.toString();

这是我的C#代码:

        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] hashValue;
        byte[] message = UE.GetBytes(MyString);

        SHA512Managed hashString = new SHA512Managed();
        string hex = "";

        hashValue = hashString.ComputeHash(message);
        foreach (byte x in hashValue)
        {
            hex += String.Format("{0:x2}", x);

        }
        return hex;

问题在哪里? Thx很多人

Where is the problem ? Thx much guys

更新

如果我不指定编码类型,它假设我认为Unicode。结果是这样的(没有指定任何内容):

If i don't specify encoding type, it supposes Unicode i think. Result is this (without specifying anything):

Java SHA: a99951079450e0bf3cf790872336b3269da580b62143af9cfa27aef42c44ea09faa83e1fbddfd1135e364ae62eb373c53ee4e89c69b54a7d4d268cc2274493a8

C# SHA: 70e6eb559cbb062b0c865c345b5f6dbd7ae9c2d39169571b6908d7df04642544c0c4e6e896e6c750f9f135ad05280ed92b9ba349de12526a28e7642721a446aa

相反,如果我在Java中指定UTF-16:

Instead, if i specify UTF-16 in Java:

Java UTF-16: SHA f7a587d55916763551e9fcaafd24d0995066371c41499fcb04614325cd9d829d1246c89af44b98034b88436c8acbd82cd13ebb366d4ab81b4942b720f02b0d9b

总是不同!!!

推荐答案

UnicodeEncoding 在C#中使用对应于小端 UTF-16编码,而Java中的UTF-16对应于 big-endian UTF-16编码。另一个区别是,如果您不要求,C#不会输出字节顺序标记(在API中称为前导码),而Java中的UTF-16始终会生成它。要使两个程序兼容,您可以使Java也使用小端UTF-16:

The UnicodeEncoding in C# you use corresponds to the little-endian UTF-16 encoding, while "UTF-16" in Java corresponds to the big-endian UTF-16 encoding. Another difference is that C# doesn't output the Byte Order Marker (called "preamble" in the API) if you don't ask for it, while "UTF-16" in Java generates it always. To make the two programs compatible you can make Java also use the little-endian UTF-16:

digest.update(MyString.getBytes("UTF-16LE"));

或者您可以切换到其他一些熟知的编码,如UTF-8。

Or you could switch to some other well known encoding, like UTF-8.

这篇关于字符串SHA-512编码:C#和JAVA结果不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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