我正在尝试读取UTF-16编码方案中的字符串并对其执行MD5哈希处理。但奇怪的是,当我尝试这样做时,Java和C#会返回不同的结果。
以下是Java中的一段代码:
public static void main(String[] args) {
String str = "preparar mantecado con coca cola";
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(str.getBytes("UTF-16"));
byte[] hash = digest.digest();
String output = "";
for(byte b: hash){
output += Integer.toString( ( b & 0xff ) + 0x100, 16).substring( 1 );
}
System.out.println(output);
} catch (Exception e) {
}
}输出为:249ece65145dca34ed310445758e5504
以下是C#中的一段代码:
public static string GetMD5Hash()
{
string input = "preparar mantecado con coca cola";
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.Unicode.GetBytes(input);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}
string output= s.ToString();
Console.WriteLine(output);
}这个输出是:c04d0f518ba2555977fa1ed7f93ae2b3
我不确定,为什么产出不一样。我们如何改变上面的代码片段,以便它们都返回相同的输出结果?