Tweaks to Enum::FormatName to make it faster/smaller
[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 #if !NET_2_0
47         internal enum DataProtectionScope {
48                 CurrentUser,
49                 LocalMachine
50         }
51 #endif
52
53         internal static class ManagedProtection {
54
55 // FIXME        [KeyContainerPermission (SecurityAction.Assert, KeyContainerName = "DAPI",
56 //                      Flags = KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Create)]
57                 public static byte[] Protect (byte[] userData, byte[] optionalEntropy, DataProtectionScope scope) 
58                 {
59                         if (userData == null)
60                                 throw new ArgumentNullException ("userData");
61
62                         Rijndael aes = Rijndael.Create ();
63                         aes.KeySize = 128;
64
65                         byte[] encdata = null;
66                         using (MemoryStream ms = new MemoryStream ()) {
67                                 ICryptoTransform t = aes.CreateEncryptor ();
68                                 using (CryptoStream cs = new CryptoStream (ms, t, CryptoStreamMode.Write)) {
69                                         cs.Write (userData, 0, userData.Length);
70                                         cs.Close ();
71                                         encdata = ms.ToArray ();
72                                 }
73                         }
74
75                         byte[] key = null;
76                         byte[] iv = null;
77                         byte[] secret = null;
78                         byte[] header = null;
79                         SHA256 hash = SHA256.Create ();
80
81                         try {
82                                 key = aes.Key;
83                                 iv = aes.IV;
84                                 secret = new byte[1 + 1 + 16 + 1 + 16 + 1 + 32];
85
86                                 byte[] digest = hash.ComputeHash (userData);
87                                 if ((optionalEntropy != null) && (optionalEntropy.Length > 0)) {
88                                         // the same optionalEntropy will be required to get the data back
89                                         byte[] mask = hash.ComputeHash (optionalEntropy);
90                                         for (int i = 0; i < 16; i++) {
91                                                 key[i] ^= mask[i];
92                                                 iv[i] ^= mask[i + 16];
93                                         }
94                                         secret[0] = 2; // entropy
95                                 } else {
96                                         secret[0] = 1; // without entropy
97                                 }
98
99                                 secret[1] = 16; // key size
100                                 Buffer.BlockCopy (key, 0, secret, 2, 16);
101                                 secret[18] = 16; // iv size
102                                 Buffer.BlockCopy (iv, 0, secret, 19, 16);
103                                 secret[35] = 32; // digest size
104                                 Buffer.BlockCopy (digest, 0, secret, 36, 32);
105
106                                 RSAOAEPKeyExchangeFormatter formatter = new RSAOAEPKeyExchangeFormatter (GetKey (scope));
107                                 header = formatter.CreateKeyExchange (secret);
108                         }
109                         finally {
110                                 if (key != null) {
111                                         Array.Clear (key, 0, key.Length);
112                                         key = null;
113                                 }
114                                 if (secret != null) {
115                                         Array.Clear (secret, 0, secret.Length);
116                                         secret = null;
117                                 }
118                                 if (iv != null) {
119                                         Array.Clear (iv, 0, iv.Length);
120                                         iv = null;
121                                 }
122                                 aes.Clear ();
123                                 hash.Clear ();
124                         }
125
126                         byte[] result = new byte[header.Length + encdata.Length];
127                         Buffer.BlockCopy (header, 0, result, 0, header.Length);
128                         Buffer.BlockCopy (encdata, 0, result, header.Length, encdata.Length);
129                         return result;
130                 }
131
132 // FIXME        [KeyContainerPermission (SecurityAction.Assert, KeyContainerName = "DAPI",
133 //                      Flags = KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Decrypt)]
134                 public static byte[] Unprotect (byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope) 
135                 {
136                         if (encryptedData == null)
137                                 throw new ArgumentNullException ("encryptedData");
138
139                         byte[] decdata = null;
140
141                         Rijndael aes = Rijndael.Create ();
142                         RSA rsa = GetKey (scope);
143                         int headerSize = (rsa.KeySize >> 3);
144                         bool valid1 = (encryptedData.Length >= headerSize);
145                         if (!valid1)
146                                 headerSize = encryptedData.Length;
147
148                         byte[] header = new byte[headerSize];
149                         Buffer.BlockCopy (encryptedData, 0, header, 0, headerSize);
150
151                         byte[] secret = null;
152                         byte[] key = null;
153                         byte[] iv = null;
154                         bool valid2 = false;
155                         bool valid3 = false;
156                         bool valid4 = false;
157                         SHA256 hash = SHA256.Create ();
158
159                         try {
160                                 try {
161                                         RSAOAEPKeyExchangeDeformatter deformatter = new RSAOAEPKeyExchangeDeformatter (rsa);
162                                         secret = deformatter.DecryptKeyExchange (header);
163                                         valid2 = (secret.Length == 68);
164                                 }
165                                 catch {
166                                         valid2 = false;
167                                 }
168
169                                 if (!valid2)
170                                         secret = new byte[68];
171
172                                 // known values for structure (version 1 or 2)
173                                 valid3 = ((secret[1] == 16) && (secret[18] == 16) && (secret[35] == 32));
174
175                                 key = new byte [16];
176                                 Buffer.BlockCopy (secret, 2, key, 0, 16);
177                                 iv = new byte [16];
178                                 Buffer.BlockCopy (secret, 19, iv, 0, 16);
179
180                                 if ((optionalEntropy != null) && (optionalEntropy.Length > 0)) {
181                                         // the decrypted data won't be valid if the entropy isn't
182                                         // the same as the one used to protect (encrypt) it
183                                         byte[] mask = hash.ComputeHash (optionalEntropy);
184                                         for (int i = 0; i < 16; i++) {
185                                                 key[i] ^= mask[i];
186                                                 iv[i] ^= mask[i + 16];
187                                         }
188                                         valid3 &= (secret[0] == 2);     // with entropy
189                                 } else {
190                                         valid3 &= (secret[0] == 1);     // without entropy
191                                 }
192
193                                 using (MemoryStream ms = new MemoryStream ()) {
194                                         ICryptoTransform t = aes.CreateDecryptor (key, iv);
195                                         using (CryptoStream cs = new CryptoStream (ms, t, CryptoStreamMode.Write)) {
196                                                 try {
197                                                         cs.Write (encryptedData, headerSize, encryptedData.Length - headerSize);
198                                                         cs.Close ();
199                                                 }
200                                                 catch {
201                                                         // whatever, we keep going
202                                                 }
203                                         }
204                                         decdata = ms.ToArray ();
205                                 }
206
207                                 byte[] digest = hash.ComputeHash (decdata);
208                                 valid4 = true;
209                                 for (int i=0; i < 32; i++) {
210                                         if (digest [i] != secret [36 + i])
211                                                 valid4 = false;
212                                 }
213                         }
214                         finally {
215                                 if (key != null) {
216                                         Array.Clear (key, 0, key.Length);
217                                         key = null;
218                                 }
219                                 if (secret != null) {
220                                         Array.Clear (secret, 0, secret.Length);
221                                         secret = null;
222                                 }
223                                 if (iv != null) {
224                                         Array.Clear (iv, 0, iv.Length);
225                                         iv = null;
226                                 }
227                                 aes.Clear ();
228                                 hash.Clear ();
229                         }
230
231                         // single point of error (also limits timing informations)
232                         if (!valid1 || !valid2 || !valid3 || !valid4) {
233                                 if (decdata != null) {
234                                         Array.Clear (decdata, 0, decdata.Length);
235                                         decdata = null;
236                                 }
237                                 throw new CryptographicException (Locale.GetText ("Invalid data."));
238                         }
239                         return decdata;
240                 }
241
242                 // private stuff
243
244                 private static RSA user;
245                 private static RSA machine;
246
247                 private static RSA GetKey (DataProtectionScope scope)
248                 {
249                         switch (scope) {
250                         case DataProtectionScope.CurrentUser:
251                                 if (user == null) {
252                                         CspParameters csp = new CspParameters ();
253                                         csp.KeyContainerName = "DAPI";
254                                         user = new RSACryptoServiceProvider (1536, csp);
255                                 }
256                                 return user;
257                         case DataProtectionScope.LocalMachine:
258                                 if (machine == null) {
259                                         CspParameters csp = new CspParameters ();
260                                         csp.KeyContainerName = "DAPI";
261                                         csp.Flags = CspProviderFlags.UseMachineKeyStore;
262                                         machine = new RSACryptoServiceProvider (1536, csp);
263                                 }
264                                 return machine;
265                         default:
266                                 throw new CryptographicException (Locale.GetText ("Invalid scope."));
267                         }
268                 }
269         } 
270 }