UnityEssentials
Small but useful tools and features for Unity
SD_Encoder.cs
Go to the documentation of this file.
1 // MIT License
2 //
3 // Copyright (c) 2020 Bronson Zgeb
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
11 //
12 // The above copyright notice and this permission notice shall be included in all
13 // copies or substantial portions of the Software.
14 //
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 // SOFTWARE.
22 
23 
24 // Significant parts of the code are extracted from this GitHub repository: https://github.com/BayatGames/SaveGameFree and https://github.com/UnityTechnologies/UniteNow20-Persistent-Data
25 
26 
27 using System;
28 using System.Text;
29 using System.Security.Cryptography;
30 using System.IO;
31 using System.Linq;
32 
34 {
35 
40  public class SD_Encoder
41  {
42 
43  private const int Keysize = 256;
44  private const int DerivationIterations = 1000;
45 
51  public string Encode ( string input, string password )
52  {
53  #if !UNITY_WSA || !UNITY_WINRT
54  var saltStringBytes = Generate256BitsOfRandomEntropy ();
55  var ivStringBytes = Generate256BitsOfRandomEntropy ();
56  var plainTextBytes = Encoding.UTF8.GetBytes ( input );
57  var passPhrase = new Rfc2898DeriveBytes ( password, saltStringBytes, DerivationIterations );
58  var keyBytes = passPhrase.GetBytes ( Keysize / 8 );
59  using ( var symmetricKey = new RijndaelManaged () )
60  {
61  symmetricKey.BlockSize = 256;
62  symmetricKey.Mode = CipherMode.CBC;
63  symmetricKey.Padding = PaddingMode.PKCS7;
64  using ( var encryptor = symmetricKey.CreateEncryptor ( keyBytes, ivStringBytes ) )
65  {
66  using ( var memoryStream = new MemoryStream () )
67  {
68  using ( var cryptoStream = new CryptoStream ( memoryStream, encryptor, CryptoStreamMode.Write ) )
69  {
70  cryptoStream.Write ( plainTextBytes, 0, plainTextBytes.Length );
71  cryptoStream.FlushFinalBlock ();
72  var cipherTextBytes = saltStringBytes;
73  cipherTextBytes = cipherTextBytes.Concat ( ivStringBytes ).ToArray ();
74  cipherTextBytes = cipherTextBytes.Concat ( memoryStream.ToArray () ).ToArray ();
75  memoryStream.Close ();
76  cryptoStream.Close ();
77  return Convert.ToBase64String ( cipherTextBytes );
78  }
79  }
80  }
81  }
82  #else
83  return Convert.ToBase64String ( Encoding.UTF8.GetBytes ( input ) );
84  #endif
85  }
86 
92  public string Decode ( string input, string password )
93  {
94  #if !UNITY_WSA || !UNITY_WINRT
95  var cipherTextBytesWithSaltAndIv = Convert.FromBase64String ( input );
96  var saltStringBytes = cipherTextBytesWithSaltAndIv.Take ( Keysize / 8 ).ToArray ();
97  var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip ( Keysize / 8 ).Take ( Keysize / 8 ).ToArray ();
98  var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip ( ( Keysize / 8 ) * 2 ).Take ( cipherTextBytesWithSaltAndIv.Length - ( ( Keysize / 8 ) * 2 ) ).ToArray ();
99  var passPhrase = new Rfc2898DeriveBytes ( password, saltStringBytes, DerivationIterations );
100  var keyBytes = passPhrase.GetBytes ( Keysize / 8 );
101  using ( var symmetricKey = new RijndaelManaged () )
102  {
103  symmetricKey.BlockSize = 256;
104  symmetricKey.Mode = CipherMode.CBC;
105  symmetricKey.Padding = PaddingMode.PKCS7;
106  using ( var decryptor = symmetricKey.CreateDecryptor ( keyBytes, ivStringBytes ) )
107  {
108  using ( var memoryStream = new MemoryStream ( cipherTextBytes ) )
109  {
110  using ( var cryptoStream = new CryptoStream ( memoryStream, decryptor, CryptoStreamMode.Read ) )
111  {
112  var plainTextBytes = new byte[cipherTextBytes.Length];
113  var decryptedByteCount = cryptoStream.Read ( plainTextBytes, 0, plainTextBytes.Length );
114  memoryStream.Close ();
115  cryptoStream.Close ();
116  return Encoding.UTF8.GetString ( plainTextBytes, 0, decryptedByteCount );
117  }
118  }
119  }
120  }
121  #else
122  return Encoding.UTF8.GetString ( Convert.FromBase64String ( input ) );
123  #endif
124  }
125 
126  #if !UNITY_WSA || !UNITY_WINRT
127  private static byte[] Generate256BitsOfRandomEntropy ()
128  {
129  var randomBytes = new byte[32];
130  var rngCsp = new RNGCryptoServiceProvider ();
131  rngCsp.GetBytes ( randomBytes );
132  return randomBytes;
133  }
134  #endif
135 
136  }
137 
138 }
Simple Encoder used by the SaveData class.
Definition: SD_Encoder.cs:41
string Decode(string input, string password)
Decode the specified input with password.
Definition: SD_Encoder.cs:92
static byte[] Generate256BitsOfRandomEntropy()
Definition: SD_Encoder.cs:127
string Encode(string input, string password)
Encode the specified input with password.
Definition: SD_Encoder.cs:51