C# Create a hash for a byte array or image


Possible Duplicate:
How do I generate a hashcode from a byte array in c#

In C#, I need to create a Hash of an image to ensure it is unique in storage.

I can easily convert it to a byte array, but unsure how to proceed from there.

Are there any classes in the .NET framework that can assist me, or is anyone aware of some efficient algorithms to create such a unique hash?

Best Solution

There's plenty of hashsum providers in .NET which create cryptographic hashes - which satisifies your condition that they are unique (for most purposes collision-proof). They are all extremely fast and the hashing definitely won't be the bottleneck in your app unless you're doing it a trillion times over.

Personally I like SHA1:

public static string GetHashSHA1(this byte[] data)
    using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider())
        return string.Concat(sha1.ComputeHash(data).Select(x => x.ToString("X2")));

Even when people say one method might be slower than another, it's all in relative terms. A program dealing with images definitely won't notice the microsecond process of generating a hashsum.

And regarding collisions, for most purposes this is also irrelevant. Even "obsolete" methods like MD5 are still highly useful in most situations. Only recommend not using it when the security of your system relies on preventing collisions.