chunk 1: core gameplay scripts scenes runtime assets
This commit is contained in:
74
Assets/Scripts/Utilities/SecurePlayerPrefs.cs
Normal file
74
Assets/Scripts/Utilities/SecurePlayerPrefs.cs
Normal file
@@ -0,0 +1,74 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using UnityEngine;
|
||||
|
||||
public static class SecurePlayerPrefs
|
||||
{
|
||||
private static readonly byte[] salt = new byte[] { 0x13, 0x24, 0x37, 0x48, 0x59, 0x6A, 0x7B, 0x8C };
|
||||
private static readonly byte[] key = new byte[] { 0x6D, 0x5B, 0x35, 0x81, 0x49, 0x93, 0xD8, 0x10, 0x52, 0x7E, 0x2B, 0x19, 0x4C, 0xFA, 0x67, 0x8A };
|
||||
|
||||
public static void SetString(string key, string value)
|
||||
{
|
||||
byte[] encrypted = EncryptStringToBytes(value);
|
||||
string encoded = Convert.ToBase64String(encrypted);
|
||||
PlayerPrefs.SetString(key, encoded);
|
||||
}
|
||||
|
||||
public static string GetString(string key, string defaultValue = "")
|
||||
{
|
||||
string encoded = PlayerPrefs.GetString(key, defaultValue);
|
||||
byte[] encrypted = Convert.FromBase64String(encoded);
|
||||
string value = DecryptStringFromBytes(encrypted);
|
||||
return value;
|
||||
}
|
||||
|
||||
private static byte[] EncryptStringToBytes(string plainText)
|
||||
{
|
||||
byte[] encrypted;
|
||||
using (Aes aesAlg = Aes.Create())
|
||||
{
|
||||
aesAlg.Key = key;
|
||||
aesAlg.IV = salt;
|
||||
|
||||
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
|
||||
|
||||
using (MemoryStream msEncrypt = new MemoryStream())
|
||||
{
|
||||
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
|
||||
{
|
||||
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
|
||||
{
|
||||
swEncrypt.Write(plainText);
|
||||
}
|
||||
encrypted = msEncrypt.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
return encrypted;
|
||||
}
|
||||
|
||||
private static string DecryptStringFromBytes(byte[] cipherText)
|
||||
{
|
||||
string plaintext = null;
|
||||
using (Aes aesAlg = Aes.Create())
|
||||
{
|
||||
aesAlg.Key = key;
|
||||
aesAlg.IV = salt;
|
||||
|
||||
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
|
||||
|
||||
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
|
||||
{
|
||||
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
|
||||
{
|
||||
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
|
||||
{
|
||||
plaintext = srDecrypt.ReadToEnd();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return plaintext;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user