Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I calculate CRC32 of a string

Tags:

.net

crc32

How do I calculate the CRC32 (Cyclic Redundancy Checksum) of a string in .NET?

like image 483
Nick Berardi Avatar asked Aug 11 '08 19:08

Nick Berardi


People also ask

How do you find the CRC of a string?

The crc32() function calculates a 32-bit CRC (cyclic redundancy checksum) for a string. This function can be used to validate data integrity. Tip: To ensure that you get the correct string representation from the crc32() function, you'll need to use the %u formatter of the printf() or sprintf() function.

How many bits is CRC32?

CRC32 is an error-detecting function that uses a CRC32 algorithm to detect changes between source and target data. The CRC32 function converts a variable-length string into an 8-character string that is a text representation of the hexadecimal value of a 32 bit-binary sequence.

How do I check my CRC32 checksum?

Right-click the file you wish to get the CRC-32 for. A context menu appears. Select the CRC SHA submenu entry. Select any of the available algorithms: CRC-32, CRC-64, SHA-1 or SHA-256 to calculate the respective checksum, or select "*" to calculate all of them and additionally BLAKE2sp.


2 Answers

This guy seems to have your answer.

https://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net

And in case the blog ever goes away or breaks the url, here's the github link:

https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/Security/Cryptography/Crc32.cs


Usage of the Crc32 class from the blog post:

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); 
like image 122
Pete Avatar answered Sep 20 '22 11:09

Pete


Since you seem to be looking to calculate the CRC32 of a string (rather than a file) there's a good example here: https://rosettacode.org/wiki/CRC-32#C.23

The code should it ever disappear:

/// <summary> /// Performs 32-bit reversed cyclic redundancy checks. /// </summary> public class Crc32 {     #region Constants     /// <summary>     /// Generator polynomial (modulo 2) for the reversed CRC32 algorithm.      /// </summary>     private const UInt32 s_generator = 0xEDB88320;     #endregion      #region Constructors     /// <summary>     /// Creates a new instance of the Crc32 class.     /// </summary>     public Crc32()     {         // Constructs the checksum lookup table. Used to optimize the checksum.         m_checksumTable = Enumerable.Range(0, 256).Select(i =>         {             var tableEntry = (uint)i;             for (var j = 0; j < 8; ++j)             {                 tableEntry = ((tableEntry & 1) != 0)                     ? (s_generator ^ (tableEntry >> 1))                      : (tableEntry >> 1);             }             return tableEntry;         }).ToArray();     }     #endregion      #region Methods     /// <summary>     /// Calculates the checksum of the byte stream.     /// </summary>     /// <param name="byteStream">The byte stream to calculate the checksum for.</param>     /// <returns>A 32-bit reversed checksum.</returns>     public UInt32 Get<T>(IEnumerable<T> byteStream)     {         try         {             // Initialize checksumRegister to 0xFFFFFFFF and calculate the checksum.             return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) =>                        (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));         }         catch (FormatException e)         {             throw new CrcException("Could not read the stream out as bytes.", e);         }         catch (InvalidCastException e)         {             throw new CrcException("Could not read the stream out as bytes.", e);         }         catch (OverflowException e)         {             throw new CrcException("Could not read the stream out as bytes.", e);         }     }     #endregion      #region Fields     /// <summary>     /// Contains a cache of calculated checksum chunks.     /// </summary>     private readonly UInt32[] m_checksumTable;      #endregion } 

and to use it:

var arrayOfBytes = Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog");  var crc32 = new Crc32(); Console.WriteLine(crc32.Get(arrayOfBytes).ToString("X")); 

You can test the input / output values here: https://crccalc.com/

like image 43
SharpC Avatar answered Sep 22 '22 11:09

SharpC