Course contentsShow
← Unity Game Development
Lesson 748 of 82811. Performance and Data PersistenceFree lesson

Encrypting Save Files for Data Integrity

Apply simple cryptographic techniques to your serialized data streams to prevent players from easily modifying their save files with external editors.

In this lesson, you’ll learn how to secure your serialized game data against simple tampering by applying a basic XOR cipher to your save file streams.

Why Encrypt Save Files?

Even if you use JsonUtility to save progress to local disk storage, the resulting file is a plain-text JSON string. Anyone can open your save file in Notepad, change their playerGold value from 100 to 999999, and ruin your game's balance. While true security requires professional-grade encryption, we can implement an "obfuscation" layer using an XOR operation to prevent casual modification.

The XOR Approach

The XOR (exclusive OR) operation is a bitwise logic gate. If you XOR a piece of data with a "key" once, it becomes garbled. If you XOR that same garbled data with the exact same key again, it reverts to the original data. This is perfect for a stream: you encrypt the bytes as you write them and decrypt them as you read them back into your JsonUtility parser.

Implementation Pattern

Instead of writing your JSON string directly to File.WriteAllText, you convert your string to a byte[] and process it:

public byte[] EncryptDecrypt(byte[] data, string key)
{
    byte[] result = new byte[data.Length];
    for (int i = 0; i < data.Length; i++)
    {
        // XOR the byte with a character from our key (cycling through the key)
        result[i] = (byte)(data[i] ^ key[i % key.Length]);
    }
    return result;
}

When saving, convert your JSON to a byte array, pass it through EncryptDecrypt, and use File.WriteAllBytes to save the scrambled data. When loading, read the bytes, run them through the same function (which acts as the decryptor), and convert the resulting bytes back into a string to be parsed by JsonUtility.

Because this logic is symmetrical, a single function handles both reading and writing. This adds a layer of "data integrity," ensuring that a casual player can no longer edit the file, as it will appear as unreadable binary noise to any standard text editor.

Key Takeaway: By passing your serialized data through an XOR bitwise operation using a secret key, you convert plain-text files into obfuscated binary streams, preventing players from easily modifying their save data with external tools.