Calculating CRC-32 in C# and .NET
Just a few days ago I found myself needing to calculate a CRC-32 in .NET. With so many facilities available I was a little shocked that there was nothing built-in to do it so knocked up something myself.
GitHub has the latest version of Crc32
Because unsigned ints aren’t CLS compliant it won’t play well with VB.Net and implementing the HashAlgorithm might lead people to believe it’s suitable for signing – it isn’t. CRC-32’s are only any good for checksums along the lines of WinZIP, RAR etc. and certainly shouldn’t come near a password and instead consider SHA-512 or similar.
As well as using it as a HashAlgorithm with block processing you can also access the static method Compute although there is an overhead with every call building the table with that. If neither option suits you needs cut ‘n splice it to something that does.
If using the Compute methods multiple times for the same hash you *must* XOR (~) the current hash when passing it in to the next subsequent call’s seed parameter.
To compute the hash for a file simply:
Crc32 crc32 = new Crc32();
String hash = String.Empty;
using (FileStream fs = File.Open("c:\\myfile.txt", FileMode.Open))
foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToLower();
Console.WriteLine("CRC-32 is {0}", hash);
[)amien
17 responses