Game Development Reference

In-Depth Information

This algorithm has also been used to detect any tampering done to data files for

games (or any software application for that matter). Checksum values are typical-

ly created for all files before a game ships; those pre-calculated values are checked

against the runtime calculated version when the game launches and detect

whether data has been modified from its original state.

This chapter covers an implementation of the CRC-32 checksum algorithm in C#

and later goes on to show an alternative algorithm provided by Microsoft. The

mathematical proofs and reasoning behind this algorithm will not be covered.

Implementation

The implementation for the CRC-32 algorithm is fairly straightforward and exists

in a few flavors. The implementation provided in this chapter precalculates a

lookup table using a specified polynomial value, and the calculation is based on

the algebra of polynomials over the values (mod 2) using the cached lookup table.

The code is as follows:

public class Crc32

{

private static uint[] _lookupTable;

public uint Calculate(System.IO.Stream stream)

{

unchecked

{

uint result = 0xFFFFFFFF;

byte[] buffer = new byte[1024];

int byteCount = stream.Read(buffer, 0, 1024);

while (byteCount > 0)

{

for (int byteIndex = 0; byteIndex < byteCount; byteIndex++)

{

result = ((result) >> 8) ^

_lookupTable[(buffer[byteIndex]) ^

((result) & 0x000000FF)];

}