Skip to main content
DamienG
Code editor beside a diagram of connected services and databases

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.

Updated October 2026: Modern .NET now has a built-in option: Microsoft’s System.IO.Hashing package includes a Crc32 class with static Hash and HashToUInt32 methods. I’ve also corrected my old advice about passwords. A fast hash like SHA-512 isn’t suitable for storing passwords either; use a dedicated password-hashing function instead.

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, but it isn’t. CRC-32s are only any good for detecting accidental errors with check-sums along the lines of WinZIP, RAR etc. They offer no protection against deliberate tampering and certainly shouldn’t come near a password. If you need to check integrity against tampering, use a cryptographic hash such as SHA-256 (with an HMAC or signature if an attacker could replace the hash too). For passwords, even SHA-256 or SHA-512 is too fast; use a purpose-built password-hashing function such as Argon2id, scrypt, bcrypt or PBKDF2 as recommended by the OWASP Password Storage Cheat Sheet.

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 your 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:

var crc32 = new Crc32();
var hash = String.Empty;

using (var 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);

If you can use the System.IO.Hashing package instead, the equivalent is:

using System.IO.Hashing;

var crc32 = new Crc32();
using (var fs = File.OpenRead("c:\\myfile.txt"))
  crc32.Append(fs);

Console.WriteLine("CRC-32 is {0:x8}", crc32.GetCurrentHashAsUInt32());

[)amien

0 responses

  1. Information is only used to show your comment. See my Privacy Policy.