Sunday, June 5, 2011

Oddness with Unity3D Android's MD5 support

I ran into an odd problem when messing around with generating MD5 hashes in Unity Android recently.

When testing on my PC I was creating an MD5 object by using MD5.Create() and it worked fine. However I then published over to my Android phone to test to make sure it works, good thing I did, because I got a NullReferenceException. Looking at the code, the only thing that jumped out at me was the MD5 object wasn't being created, so I added a check for that condition, and indeed the MD5 object didn't exist. So for some reason MD5.Create() didn't work on the Android hardware.

A little bit of Googling landed me on unifycommunity.com, where I noticed the author, Matthew Wegner, wasn't using the MD5.Create() method but new'ing a MD5CryptoServiceProvider object. Curious, since they both seem to return the same object, I tried out this new method and to my amazement it worked! Horray!

Before I was about to close the book on this and forget MD5.Create() forever, I noticed my project had the Stripping Level set to use micro mscorlib. That turned on a light in my head, so out of curiosity I disabled stripping, re-enabled MD5.Create and re-published to my phone. This time MD5.Create worked.

TL;DR
MD5.Create() doesn't return an object on Unity Android when the Stripping Level is set to Micro mscorlib, but 'new MD5CryptoServiceProvider()' does. When Stripping is disabled MD5.Create() does work as expected. I haven't tested this on the iPhone but the results are probably the same.

Even Short Version:
It's seems safest to 'new MD5CryptoServiceProvider()' whenever you need an MD5 object as it appears to be the most portable.