Players modifying save files is a common concern, particularly with human-readable formats like JSON. Here are several approaches to protect your save data:
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;
}
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);
}
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.
Learn techniques for managing game data, including save systems, configuration, and networked multiplayer.