String SHA-512 Encoding: C# and JAVA result is different

两盒软妹~` 提交于 2019-12-03 00:24:41

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"));

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

Here,

digest.update(MyString.getBytes()); 

you should be explicitly specifying the desired character encoding in String#getBytes() method. It will otherwise default to the platform default charset as is been obtained by Charset#defaultCharset().

Fix it accordingly:

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

It should at least be the same charset as UnicodeEncoding is internally using.


Unrelated to the concrete problem, Java has also an enhanced for loop and a String#format().

The reason is probably that you did not specify the encoding to use when converting the string to bytes, java uses the platform default encoding, while UnicodeEncoding seems to use utf-16.

Edit:

The documentation for UnicodeEncoding says

This constructor creates an instance that uses the little endian byte order, provides a Unicode byte order mark, and does not throw an exception when an invalid encoding is detected.

Javas "utf-16" however seems to default to big endian byte order. With character encodings its better to be really specific, there is an UnicodeEncoding constructor taking two boolean specifiyng byte order, while in java there is also "utf-16le" and "utf-16be". You could try the following in c#

new UnicodeEncoding(true, false) // big endian, no byte order mark

and in java

myyString.getBytes("utf-16be")

Or even better use "utf-8" / Encoding.UTF8 in both cases since it is not affected by different byteorders.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!