-
Notifications
You must be signed in to change notification settings - Fork 12
/
SecurePlayerPrefs.cs
398 lines (347 loc) · 10.9 KB
/
SecurePlayerPrefs.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
/**
* Securely save player preferences in Unity3d projects.
* This uses DES Encryption to encrypt your player prefs.
*
* @author Rawand Fatih ([email protected])
* Copyright © 2014 Rawand Fatih
*/
public class SecurePlayerPrefs {
/*
* The key is splited to three parts:
* - The prefix, first part.
* - Three randomly generated characters for each device.
* - The suffix, the end part of the key.
* These constants are used in storing the random part for each device,
* And for the prefs it uses the random number instead of PRIVATE_KEY_RAND.
*/
private static readonly string PRIVATE_KEY_PREFIX = "abcd";
private static readonly string PRIVATE_KEY_RAND = "efg";
private static readonly string PRIVATE_KEY_SUFFIX = "h";
// The private key of DES encryption.
private static string privateKey;
// Is the secure prefs initialized.
private static bool isInit = false;
// Your private key to store the randomly generated key for each device.
private static readonly string RAND_KEY = "abcdefgh";
// Should errors/exceptions be logged.
private static bool logErrorsEnabled = false;
/**
* Initializes the encryptor. If its the frist time, it will generate
* a random 3 digit number and puts it between private key and its appendix.
* If this was initialized on this device before, it will load it and create
* the private key.
*
* You can also copy players current preferences if your moving from Unity's
* PlayerPrefs to this secure one.
*/
public static void Init() {
if(HasKey(RAND_KEY)) {
privateKey = PRIVATE_KEY_PREFIX + PRIVATE_KEY_RAND + PRIVATE_KEY_SUFFIX;
privateKey = GetString(RAND_KEY);
privateKey = PRIVATE_KEY_PREFIX + privateKey + PRIVATE_KEY_SUFFIX;
} else {
int rand = UnityEngine.Random.Range(100, 1000);
privateKey = PRIVATE_KEY_PREFIX + PRIVATE_KEY_RAND + PRIVATE_KEY_SUFFIX;
SetInt(RAND_KEY, rand);
privateKey = PRIVATE_KEY_PREFIX + rand + PRIVATE_KEY_SUFFIX;
/*
* Add copying PlayerPrefs to SecurePlayerPrefs code here.
* See the example at GitHub. www.github.com/rawandnf/SecurePlayerPrefs
*/
}
isInit = true;
}
/**
* Is the decryptor initialized.
*/
public static bool isInitialized() {
return isInit;
}
/**
* Converts unsecure player prefs to secure player prefs.
*
* Basically translates the prefs to secure ones.
* @param keynames Is the list of keys with old and new name, [old name][new name][type].
* @param deleteOldKeys Should it delete the old keys.
*/
private static void securePlayerPrefs(string[,] keynames, bool deleteOldKeys) {
for (int i = 0; i < keynames.GetLength(0); i++) {
if (keynames[i, 2].Equals("int")) {
// Getting the integer and saving it encrypted.
int temp = PlayerPrefs.GetInt(keynames[i, 0]);
if(deleteOldKeys) {
PlayerPrefs.DeleteKey(keynames[i, 0]);
}
SetInt(keynames[i, 1], temp);
} else if (keynames[i, 2].Equals("float")) {
// Getting the float and saving it encrypted.
float temp = PlayerPrefs.GetFloat(keynames[i, 0]);
if(deleteOldKeys) {
PlayerPrefs.DeleteKey(keynames[i, 0]);
}
SetFloat(keynames[i, 1], temp);
} else {
// If not a float and int, then we take it as a string and save it encrypted.
string temp = PlayerPrefs.GetString(keynames[i, 0]);
if(deleteOldKeys) {
PlayerPrefs.DeleteKey(keynames[i, 0]);
}
SetString(keynames[i, 1], temp);
}
}
Save ();
}
/**
* Change the state of error log enabled.
*
* @param state The new state of error log enabled.
*/
public static void setLogErrorsEnabled(bool state) {
logErrorsEnabled = state;
}
/**
* Saves a string in player preferences but securly encrypted.
* @param key The preference id.
* @param val The value of the preference, it will be encrypted.
*/
public static void SetString(string key, string val) {
PlayerPrefs.SetString(key, Encrypt(val));
}
/**
* Saves a float in the player prefs securely encrypted.
* Note that everything is saved as strings, but can use methods provided
* in this class to get the float, or just get your string decrypt and parse
* it back to float.
*
* @param key The preference id.
* @param val The value of preference, it will be encrypted.
* @see {@code #SetString(key: string, val: string)}
*/
public static void SetFloat(string key, float val) {
SetString(key, val + "");
}
/**
* Saves a float in the player prefs securely encrypted.
* Note that everything is saved as strings, but can use methods provided
* in this class to get the int, or just get your string decrypt and parse
* it back to int.
*
* @param key The preference id.
* @param val The value of preference, it will be encrypted.
* @see {@code #SetString(key: string, val: string)}
*/
public static void SetInt(string key, int val) {
SetString(key, val + "");
}
/**
* Save a boolean in the player prefs.
*
* @param key The preference id.
* @param val The value of preference, it will be encrypted.
* @see {@code #SetString(key: string, val: bool)}
*/
public static void SetBool(string key, bool val) {
SetInt(key, ((val)? 1:0));
}
/**
* Get a securly encrypted text from the player preferences.
*
* @param key The id of the player preferences.
* @param defaultValue The default to return.
* @return The decrypted value or default in case of not found.
*/
public static string GetString(String key, String defaultValue) {
string s = PlayerPrefs.GetString(key, defaultValue);
if(s != defaultValue && s != "" && s != null) {
try{
return Decrypt(s);
} catch (Exception ex) {
if(logErrorsEnabled) {
Debug.Log(ex.StackTrace);
}
}
}
return defaultValue;
}
/**
* Get a securly encrypted text from the player preferences.
*
* @param key The id of the player preferences.
* @return The decrypted value or default in case of not found.
* @see {@ GetString(key : string, defaultValue : string)
*/
public static string GetString(string key) {
return GetString(key, "");
}
/**
* Get a securly encrypted int from the player preferences.
*
* @param key The id of the player preferences.
* @param defaultValue The default to return.
* @return The decrypted value or default in case of not found
*/
public static int GetInt(String key, int defaultValue) {
string s = PlayerPrefs.GetString(key);
if (s != "" && s!= null) {
try {
string d = Decrypt(s);
int i = int.Parse(d);
return i;
} catch (Exception ex) {
if(logErrorsEnabled) {
Debug.Log(ex.StackTrace);
}
}
}
return defaultValue;
}
/**
* Get a securly encrypted int from the player preferences.
*
* @param key The id of the player preferences.
* @return The decrypted value or default in case of not found.
* @see {@ GetInt(key : string, defaultValue : int)
*/
public static int GetInt(string key) {
return GetInt (key, 0);
}
/**
* Get a securly encrypted float from the player preferences.
*
* @param key The id of the player preferences.
* @param defaultValue The default to return.
* @return The decrypted value or default in case of not found
*/
public static float GetFloat(String key, float defaultValue) {
string s = PlayerPrefs.GetString(key);
if (s != "" && s!= null) {
try {
string d = Decrypt(s);
float f = float.Parse(d);
return f;
} catch (Exception ex) {
if(logErrorsEnabled) {
Debug.Log(ex.StackTrace);
}
}
}
return defaultValue;
}
/**
* Get a securly encrypted float from the player preferences.
*
* @param key The id of the player preferences.
* @return The decrypted value or default in case of not found.
* @see {@ GetFloat(key : string, defaultValue : float)
*/
public static float GetFloat(string key) {
return GetFloat (key, 0);
}
/**
* Get a securly encrypted bool from the player preferences.
*
* @param key The id of the player preferences.
* @param defaultValue the default value to return.
* @return The decrypted value or default in case of not found.
*/
public static bool GetBool(string key, bool defaultValue) {
int i = GetInt(key);
if (i == 1) {
return true;
}
return defaultValue;
}
/**
* Get a securly encrypted bool from the player preferences.
*
* @param key The id of the player preferences.
* @return The decrypted value or default in case of not found.
* @see {@ GetBool(key : string, defaultValue : bool)
*/
public static bool GetBool(string key) {
return GetBool(key, false);
}
/**
* Removes key and its corresponding value from the preferences.
*
* @param key The id of the player preferences.
*/
public static void DeleteKey(string key) {
PlayerPrefs.DeleteKey(key);
}
/**
* Removes all keys and values from the preferences.
* Use with caution.
*/
public static void DeleteAll() {
PlayerPrefs.DeleteAll();
}
/**
* Returns true if key exists in the preferences.
*
* @param key The id of the preference.
*/
public static bool HasKey(string key) {
return PlayerPrefs.HasKey(key);
}
/**
* Writes all modified preferences to disk.
*
* By default Unity writes preferences to disk on Application Quit.
* In case when the game crashes or otherwise prematuraly exits,
* you might want to write the PlayerPrefs at sensible 'checkpoints'
* in your game. This function will write to disk potentially causing
* a small hiccup, therefore it is not recommended to call during actual gameplay.
*/
public static void Save() {
PlayerPrefs.Save();
}
/**
* Decrypts a cipher with DES.
*
* @param encryptedString The cipher to decrypt.
*/
private static string Decrypt(string encryptedString) {
DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();
desProvider.Mode = CipherMode.ECB;
desProvider.Padding = PaddingMode.PKCS7;
desProvider.Key = Encoding.ASCII.GetBytes(privateKey);
using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(encryptedString)))
{
using (CryptoStream cs = new CryptoStream(stream, desProvider.CreateDecryptor(), CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs, Encoding.ASCII))
{
return sr.ReadToEnd();
}
}
}
}
/**
* Encrypt a plain text with DES.
*
* @param plainText The text to encrypt.
*/
private static string Encrypt(string plainText) {
DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();
desProvider.Mode = CipherMode.ECB;
desProvider.Padding = PaddingMode.PKCS7;
desProvider.Key = Encoding.ASCII.GetBytes(privateKey);
using (MemoryStream stream = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(stream, desProvider.CreateEncryptor(), CryptoStreamMode.Write))
{
byte[] data = Encoding.Default.GetBytes(plainText);
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock(); // <-- Add this
return Convert.ToBase64String(stream.ToArray());
}
}
}
}