Working with Data

Preventing Save File Tampering

What happens if a player tries to cheat by editing the save file? How can we prevent that?

Abstract art representing computer programming

Players modifying save files is a common concern, particularly with human-readable formats like JSON. Here are several approaches to protect your save data:

Checksum Validation

Add a checksum to your save data to detect modifications:

#include <cstdint>
#include <string>

uint32_t CalculateChecksum(
  const std::string& Data) {
  uint32_t Checksum{0};
  for (char c : Data) {
    // Simple hash function
    Checksum = (Checksum + c) * 17;
  }
  return Checksum;
}

void SaveGame(const GameState& State) {
  std::string JsonData = SerializeToJson(State);
  uint32_t Checksum = CalculateChecksum(
    JsonData);

  SaveFile File;
  File.Data = JsonData;
  File.Checksum = Checksum;
  WriteToFile("save.json", File);
}

bool LoadGame(GameState& State) {
  SaveFile File = ReadFromFile("save.json");
  if (CalculateChecksum(File.Data) != File.
    Checksum) {
    return false; // Save file was modified
  }

  State = DeserializeFromJson(File.Data);
  return true;
}

Encryption

For stronger protection, encrypt the save data:

#include <string>
#include <vector>

std::vector<char> EncryptData(
  const std::string& Data,
  const std::string& Key
) {
  std::vector<char> Encrypted;
  for (size_t i = 0;
       i < Data.length(); ++i) {
    Encrypted.push_back(
      Data[i] ^ Key[i % Key.length()]);
  }
  return Encrypted;
}

void SaveGame(const GameState& State) {
  std::string JsonData = SerializeToJson(State);
  auto Encrypted = EncryptData(
    JsonData, "SecretKey123");
  WriteToFile("save.dat", Encrypted);
}

Binary Format

Consider using binary format instead of JSON - it's harder to modify and more efficient:

void SaveBinary(const GameState& State) {
  std::ofstream File{
    "save.dat", std::ios::binary};
  File.write(
    reinterpret_cast<const char*>(&State),
    sizeof(GameState)
  );
}

Remember that determined players can still modify binary saves or break encryption. The goal is to prevent casual tampering while keeping save files efficient and reliable for honest players.

Answers to questions are automatically generated and may not have been reviewed.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 75 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2025 - All Rights Reserved