SecurePlayerPrefs is a secure wrapper for Unity's PlayerPrefs that provides encrypted data storage for sensitive information in Unity applications. It uses TripleDES encryption with device-specific key derivation to protect stored data from tampering and unauthorized access.
- Encrypted storage of strings, integers, and floating-point values
- Device-specific encryption keys
- Automatic salt generation and management
- Fallback to default values if decryption fails
- Compatible with Unity's PlayerPrefs API style
- Copy the
SecurePlayerPrefs.cs
file into your Unity project's Scripts folder
// Storing values
SecurePlayerPrefs.SetString("playerName", "John Doe");
SecurePlayerPrefs.SetInt("highScore", 1000);
SecurePlayerPrefs.SetFloat("playerHealth", 100.5f);
// Retrieving values
string name = SecurePlayerPrefs.GetString("playerName", "Default Name");
int score = SecurePlayerPrefs.GetInt("highScore", 0);
float health = SecurePlayerPrefs.GetFloat("playerHealth", 100f);
You can store complex objects by serializing them to JSON:
// Create and store a complex object
var playerData = new PlayerData
{
Name = "John Doe",
Score = 1000
};
string json = JsonUtility.ToJson(playerData);
SecurePlayerPrefs.SetString("playerData", json);
// Retrieve and deserialize the object
string savedJson = SecurePlayerPrefs.GetString("playerData");
PlayerData loadedData = JsonUtility.FromJson<PlayerData>(savedJson);
- Encryption: Uses TripleDES encryption in ECB mode with PKCS7 padding
- Key Derivation:
- Generates a unique salt for each installation
- Combines salt with device-specific identifier
- Uses SHA256 to derive the final encryption key
- Device-Specific: Data encrypted on one device cannot be decrypted on another
- The encryption key is derived from:
- A randomly generated salt (stored in PlayerPrefs)
- The device's unique identifier
- The salt is generated once per installation and reused thereafter
- Data is stored in Base64 format after encryption
- Uses standard .NET cryptography libraries
- Does not provide secure storage for the salt (stored in plain text in PlayerPrefs)
- Uses ECB mode which may not be suitable for all security requirements
- Relies on Unity's
SystemInfo.deviceUniqueIdentifier
which may change in some circumstances - No built-in key rotation mechanism
public class GameManager : MonoBehaviour
{
private void SaveGameState()
{
var gameState = new GameState
{
Level = currentLevel,
Score = playerScore,
LastSaved = DateTime.Now.ToString()
};
string json = JsonUtility.ToJson(gameState);
SecurePlayerPrefs.SetString("gameState", json);
}
private GameState LoadGameState()
{
string json = SecurePlayerPrefs.GetString("gameState", "");
return string.IsNullOrEmpty(json)
? new GameState()
: JsonUtility.FromJson<GameState>(json);
}
}