In this lesson, you will learn how to implement checksum validation to detect unauthorized modifications or accidental corruption in your player save files.
The Concept of a Checksum
A checksum is essentially a digital fingerprint of your data. When you save your game state, you run the serialized data (your JSON or binary file) through a hashing algorithm—like SHA-256—to produce a unique, fixed-length string of characters. You store this checksum alongside your save file.
When the game loads the file later, it performs the exact same calculation on the saved data. If the resulting hash matches the one you stored, the file is authentic. If even a single byte of the save data was changed (by a player editing the file or a disk read error), the resulting hash will be completely different, allowing your game to reject the tampered file.
Implementation in Unity
To implement this, you can use the System.Security.Cryptography namespace. Here is how you might generate a hash for your save data:
using System.Security.Cryptography;
using System.Text;
public string GenerateChecksum(string data)
{
using (SHA256 sha256 = SHA256.Create())
{
byte[] inputBytes = Encoding.UTF8.GetBytes(data);
byte[] hashBytes = sha256.ComputeHash(inputBytes);
return Convert.ToBase64String(hashBytes);
}
}
When saving, concatenate your JSON string with its checksum—perhaps in a wrapper class—and write it to disk. During the loading phase, verify the integrity before deserializing:
public bool IsSaveValid(string savedData, string storedChecksum)
{
string currentChecksum = GenerateChecksum(savedData);
return currentChecksum == storedChecksum;
}
Why This Matters
While encryption hides data from prying eyes, checksums provide data integrity. Without a checksum, a player could modify their "Gold" value in a plain-text JSON file. Even if you encrypt your file, a checksum provides a secondary layer of security, ensuring that the file hasn't been corrupted or altered by external tools. If the validation fails, you should treat the save as corrupted and potentially revert to a backup or prompt the player to reset their progress.
Key Takeaway: A checksum acts as an immutable seal; by comparing a file's current hash against a stored original, you can programmatically detect and reject any unauthorized alteration of your save data.