views:

90

answers:

2

Hi,

I'm hashing some data in Action Script then comparing the hash to one computed in C#, but they don't match.

Anyone know why?

Here's what I do in Action script:

    var hash : String = MD5.hash(theString);

And here's what I do in C#:

    var md5Hasher = MD5.Create();
    byte[] data = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(theSameString));
    var sBuilder = new StringBuilder();

    for (int i = 0; i < data.Length; i++)
    {
        sBuilder.Append(data[i].ToString("x2"));
    }
    var hash = sBuidler.ToString();

I'm thinking it's an encoding thing, but can't put my finger on it... let me know!

-Ev

A: 

Strings in ActionScript are in UTF-16 encoding.

This contradicts the accepted answer on [this earlier question about MD5 in ActionScript and PHP](http://stackoverflow.com/questions/2225474) which claims that ActionScript uses UTF-8. So who’s right?
Timwi
In this case, it turns out that it was encoded as ISO-8859-1Thanks for the help!
Ev
@Jeff Mattfield. That's not relevant to the problem. That's how flash stores strings *internally*. If you have a string and want to get the bytes, you would call ByteArray::writeUFT or ByteArray::writeUTFBytes, which encodes the strings using UTF-8.
Juan Pablo Califano
@Ev. I'd say your string was iso-8859-1 encoded on the C# side.
Juan Pablo Califano
My apologies. Thanks for the clarification.
+4  A: 

ActionScript must be using a different string encoding, but it is unclear to me which (I tried to google but it’s very hard to find).

Therefore, I recommend you try the following:

Console.WriteLine(ToHex(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("ä"))));
Console.WriteLine(ToHex(MD5.Create().ComputeHash(Encoding.Unicode.GetBytes("ä"))));
Console.WriteLine(ToHex(MD5.Create().ComputeHash(Encoding.GetEncoding("ISO-8859-1").GetBytes("ä"))));

(Of course, ToHex is the function that you already wrote to turn things into into hexadecimal:)

static string ToHex(byte[] data)
{
    var sBuilder = new StringBuilder();
    for (int i = 0; i < data.Length; i++)
        sBuilder.Append(data[i].ToString("x2"));
    return sBuilder.ToString();
}

And then check to see which of the three hashes you get is the same as the one in ActionScript. Then you’ll know which encoding ActionScript uses.

Timwi
Thanks I used your advice to find the right encoding.It turns out:byte[] data = md5Hasher.ComputeHash(Encoding.GetEncoding("ISO-8859-1").GetBytes(input));is the correct one.THANKS!-Ev
Ev