[System] Fix a few type members on WatchOS
[mono.git] / mcs / class / System.Security / Mono.Security.Cryptography / ManagedProtection.cs
1 //
2 // ManagedProtection.cs - 
3 //      Protect (encrypt) data without (user involved) key management
4 //
5 // Author:
6 //      Sebastien Pouliot  <sebastien@ximian.com>
7 //
8 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29
30 using System;
31 using System.IO;
32 using System.Runtime.InteropServices;
33 using System.Security;
34 using System.Security.Cryptography;
35 using System.Security.Permissions;
36
37 namespace Mono.Security.Cryptography {
38
39         // Managed Protection Implementation
40         //
41         // Features
42         // * Separate RSA 1536 bits keypairs for each user and the computer
43         // * AES 128 bits encryption (separate key for each data protected)
44         // * SHA256 digest to ensure integrity
45
46
47         internal static class ManagedProtection {
48
49 // FIXME        [KeyContainerPermission (SecurityAction.Assert, KeyContainerName = "DAPI",
50 //                      Flags = KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Create)]
51                 public static byte[] Protect (byte[] userData, byte[] optionalEntropy, DataProtectionScope scope) 
52                 {
53                         if (userData == null)
54                                 throw new ArgumentNullException ("userData");
55
56                         Rijndael aes = Rijndael.Create ();
57                         aes.KeySize = 128;
58
59                         byte[] encdata = null;
60                         using (MemoryStream ms = new MemoryStream ()) {
61                                 ICryptoTransform t = aes.CreateEncryptor ();
62                                 using (CryptoStream cs = new CryptoStream (ms, t, CryptoStreamMode.Write)) {
63                                         cs.Write (userData, 0, userData.Length);
64                                         cs.Close ();
65                                         encdata = ms.ToArray ();
66                                 }
67                         }
68
69                         byte[] key = null;
70                         byte[] iv = null;
71                         byte[] secret = null;
72                         byte[] header = null;
73                         SHA256 hash = SHA256.Create ();
74
75                         try {
76                                 key = aes.Key;
77                                 iv = aes.IV;
78                                 secret = new byte[1 + 1 + 16 + 1 + 16 + 1 + 32];
79
80                                 byte[] digest = hash.ComputeHash (userData);
81                                 if ((optionalEntropy != null) && (optionalEntropy.Length > 0)) {
82                                         // the same optionalEntropy will be required to get the data back
83                                         byte[] mask = hash.ComputeHash (optionalEntropy);
84                                         for (int i = 0; i < 16; i++) {
85                                                 key[i] ^= mask[i];
86                                                 iv[i] ^= mask[i + 16];
87                                         }
88                                         secret[0] = 2; // entropy
89                                 } else {
90                                         secret[0] = 1; // without entropy
91                                 }
92
93                                 secret[1] = 16; // key size
94                                 Buffer.BlockCopy (key, 0, secret, 2, 16);
95                                 secret[18] = 16; // iv size
96                                 Buffer.BlockCopy (iv, 0, secret, 19, 16);
97                                 secret[35] = 32; // digest size
98                                 Buffer.BlockCopy (digest, 0, secret, 36, 32);
99
100                                 RSAOAEPKeyExchangeFormatter formatter = new RSAOAEPKeyExchangeFormatter (GetKey (scope));
101                                 header = formatter.CreateKeyExchange (secret);
102                         }
103                         finally {
104                                 if (key != null) {
105                                         Array.Clear (key, 0, key.Length);
106                                         key = null;
107                                 }
108                                 if (secret != null) {
109                                         Array.Clear (secret, 0, secret.Length);
110                                         secret = null;
111                                 }
112                                 if (iv != null) {
113                                         Array.Clear (iv, 0, iv.Length);
114                                         iv = null;
115                                 }
116                                 aes.Clear ();
117                                 hash.Clear ();
118                         }
119
120                         byte[] result = new byte[header.Length + encdata.Length];
121                         Buffer.BlockCopy (header, 0, result, 0, header.Length);
122                         Buffer.BlockCopy (encdata, 0, result, header.Length, encdata.Length);
123                         return result;
124                 }
125
126 // FIXME        [KeyContainerPermission (SecurityAction.Assert, KeyContainerName = "DAPI",
127 //                      Flags = KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Decrypt)]
128                 public static byte[] Unprotect (byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope) 
129                 {
130                         if (encryptedData == null)
131                                 throw new ArgumentNullException ("encryptedData");
132
133                         byte[] decdata = null;
134
135                         Rijndael aes = Rijndael.Create ();
136                         RSA rsa = GetKey (scope);
137                         int headerSize = (rsa.KeySize >> 3);
138                         bool valid1 = (encryptedData.Length >= headerSize);
139                         if (!valid1)
140                                 headerSize = encryptedData.Length;
141
142                         byte[] header = new byte[headerSize];
143                         Buffer.BlockCopy (encryptedData, 0, header, 0, headerSize);
144
145                         byte[] secret = null;
146                         byte[] key = null;
147                         byte[] iv = null;
148                         bool valid2 = false;
149                         bool valid3 = false;
150                         bool valid4 = false;
151                         SHA256 hash = SHA256.Create ();
152
153                         try {
154                                 try {
155                                         RSAOAEPKeyExchangeDeformatter deformatter = new RSAOAEPKeyExchangeDeformatter (rsa);
156                                         secret = deformatter.DecryptKeyExchange (header);
157                                         valid2 = (secret.Length == 68);
158                                 }
159                                 catch {
160                                         valid2 = false;
161                                 }
162
163                                 if (!valid2)
164                                         secret = new byte[68];
165
166                                 // known values for structure (version 1 or 2)
167                                 valid3 = ((secret[1] == 16) && (secret[18] == 16) && (secret[35] == 32));
168
169                                 key = new byte [16];
170                                 Buffer.BlockCopy (secret, 2, key, 0, 16);
171                                 iv = new byte [16];
172                                 Buffer.BlockCopy (secret, 19, iv, 0, 16);
173
174                                 if ((optionalEntropy != null) && (optionalEntropy.Length > 0)) {
175                                         // the decrypted data won't be valid if the entropy isn't
176                                         // the same as the one used to protect (encrypt) it
177                                         byte[] mask = hash.ComputeHash (optionalEntropy);
178                                         for (int i = 0; i < 16; i++) {
179                                                 key[i] ^= mask[i];
180                                                 iv[i] ^= mask[i + 16];
181                                         }
182                                         valid3 &= (secret[0] == 2);     // with entropy
183                                 } else {
184                                         valid3 &= (secret[0] == 1);     // without entropy
185                                 }
186
187                                 using (MemoryStream ms = new MemoryStream ()) {
188                                         ICryptoTransform t = aes.CreateDecryptor (key, iv);
189                                         using (CryptoStream cs = new CryptoStream (ms, t, CryptoStreamMode.Write)) {
190                                                 try {
191                                                         cs.Write (encryptedData, headerSize, encryptedData.Length - headerSize);
192                                                         cs.Close ();
193                                                 }
194                                                 catch {
195                                                         // whatever, we keep going
196                                                 }
197                                         }
198                                         decdata = ms.ToArray ();
199                                 }
200
201                                 byte[] digest = hash.ComputeHash (decdata);
202                                 valid4 = true;
203                                 for (int i=0; i < 32; i++) {
204                                         if (digest [i] != secret [36 + i])
205                                                 valid4 = false;
206                                 }
207                         }
208                         finally {
209                                 if (key != null) {
210                                         Array.Clear (key, 0, key.Length);
211                                         key = null;
212                                 }
213                                 if (secret != null) {
214                                         Array.Clear (secret, 0, secret.Length);
215                                         secret = null;
216                                 }
217                                 if (iv != null) {
218                                         Array.Clear (iv, 0, iv.Length);
219                                         iv = null;
220                                 }
221                                 aes.Clear ();
222                                 hash.Clear ();
223                         }
224
225                         // single point of error (also limits timing informations)
226                         if (!valid1 || !valid2 || !valid3 || !valid4) {
227                                 if (decdata != null) {
228                                         Array.Clear (decdata, 0, decdata.Length);
229                                         decdata = null;
230                                 }
231                                 throw new CryptographicException (Locale.GetText ("Invalid data."));
232                         }
233                         return decdata;
234                 }
235
236                 // private stuff
237
238                 private static RSA user;
239                 private static RSA machine;
240                 private readonly static object user_lock = new object ();
241                 private readonly static object machine_lock = new object ();
242
243                 private static RSA GetKey (DataProtectionScope scope)
244                 {
245                         switch (scope) {
246                         case DataProtectionScope.CurrentUser:
247                                 if (user == null) {
248                                         lock (user_lock) {
249                                                 CspParameters csp = new CspParameters ();
250                                                 csp.KeyContainerName = "DAPI";
251                                                 user = new RSACryptoServiceProvider (1536, csp);
252                                         }
253                                 }
254                                 return user;
255                         case DataProtectionScope.LocalMachine:
256                                 if (machine == null) {
257                                         lock (machine_lock) {
258                                                 CspParameters csp = new CspParameters ();
259                                                 csp.KeyContainerName = "DAPI";
260                                                 csp.Flags = CspProviderFlags.UseMachineKeyStore;
261                                                 machine = new RSACryptoServiceProvider (1536, csp);
262                                         }
263                                 }
264                                 return machine;
265                         default:
266                                 throw new CryptographicException (Locale.GetText ("Invalid scope."));
267                         }
268                 }
269         } 
270 }