Note that there are some explanatory texts on larger screens.

plurals
  1. POUTF-16 Encoding in Java versus C#
    text
    copied!<p>I am trying to read a String in UTF-16 encoding scheme and perform MD5 hashing on it. But strangely, Java and C# are returning different results when I try to do it. </p> <p>The following is the piece of code in <strong>Java</strong>:</p> <pre><code>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 &amp; 0xff ) + 0x100, 16).substring( 1 ); } System.out.println(output); } catch (Exception e) { } } </code></pre> <p>The output for this is: <strong>249ece65145dca34ed310445758e5504</strong></p> <p>The following is the piece of code in <strong>C#</strong>:</p> <pre><code> 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); } </code></pre> <p>The output for this is: <strong>c04d0f518ba2555977fa1ed7f93ae2b3</strong></p> <p>I am not sure, why the outputs are not the same. How do we change the above piece of code, so that both of them return the same output?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload