2 // ManagedProtection.cs -
3 // Protect (encrypt) data without (user involved) key management
6 // Sebastien Pouliot <sebastien@ximian.com>
8 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
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:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
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.
32 using System.Runtime.InteropServices;
33 using System.Security;
34 using System.Security.Cryptography;
35 using System.Security.Permissions;
37 namespace Mono.Security.Cryptography {
39 // Managed Protection Implementation
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
47 internal static class ManagedProtection {
49 // FIXME [KeyContainerPermission (SecurityAction.Assert, KeyContainerName = "DAPI",
50 // Flags = KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Create)]
51 public static byte[] Protect (byte[] userData, byte[] optionalEntropy, DataProtectionScope scope)
54 throw new ArgumentNullException ("userData");
56 Rijndael aes = Rijndael.Create ();
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);
65 encdata = ms.ToArray ();
73 SHA256 hash = SHA256.Create ();
78 secret = new byte[1 + 1 + 16 + 1 + 16 + 1 + 32];
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++) {
86 iv[i] ^= mask[i + 16];
88 secret[0] = 2; // entropy
90 secret[0] = 1; // without entropy
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);
100 RSAOAEPKeyExchangeFormatter formatter = new RSAOAEPKeyExchangeFormatter (GetKey (scope));
101 header = formatter.CreateKeyExchange (secret);
105 Array.Clear (key, 0, key.Length);
108 if (secret != null) {
109 Array.Clear (secret, 0, secret.Length);
113 Array.Clear (iv, 0, iv.Length);
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);
126 // FIXME [KeyContainerPermission (SecurityAction.Assert, KeyContainerName = "DAPI",
127 // Flags = KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Decrypt)]
128 public static byte[] Unprotect (byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope)
130 if (encryptedData == null)
131 throw new ArgumentNullException ("encryptedData");
133 byte[] decdata = null;
135 Rijndael aes = Rijndael.Create ();
136 RSA rsa = GetKey (scope);
137 int headerSize = (rsa.KeySize >> 3);
138 bool valid1 = (encryptedData.Length >= headerSize);
140 headerSize = encryptedData.Length;
142 byte[] header = new byte[headerSize];
143 Buffer.BlockCopy (encryptedData, 0, header, 0, headerSize);
145 byte[] secret = null;
151 SHA256 hash = SHA256.Create ();
155 RSAOAEPKeyExchangeDeformatter deformatter = new RSAOAEPKeyExchangeDeformatter (rsa);
156 secret = deformatter.DecryptKeyExchange (header);
157 valid2 = (secret.Length == 68);
164 secret = new byte[68];
166 // known values for structure (version 1 or 2)
167 valid3 = ((secret[1] == 16) && (secret[18] == 16) && (secret[35] == 32));
170 Buffer.BlockCopy (secret, 2, key, 0, 16);
172 Buffer.BlockCopy (secret, 19, iv, 0, 16);
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++) {
180 iv[i] ^= mask[i + 16];
182 valid3 &= (secret[0] == 2); // with entropy
184 valid3 &= (secret[0] == 1); // without entropy
187 using (MemoryStream ms = new MemoryStream ()) {
188 ICryptoTransform t = aes.CreateDecryptor (key, iv);
189 using (CryptoStream cs = new CryptoStream (ms, t, CryptoStreamMode.Write)) {
191 cs.Write (encryptedData, headerSize, encryptedData.Length - headerSize);
195 // whatever, we keep going
198 decdata = ms.ToArray ();
201 byte[] digest = hash.ComputeHash (decdata);
203 for (int i=0; i < 32; i++) {
204 if (digest [i] != secret [36 + i])
210 Array.Clear (key, 0, key.Length);
213 if (secret != null) {
214 Array.Clear (secret, 0, secret.Length);
218 Array.Clear (iv, 0, iv.Length);
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);
231 throw new CryptographicException (Locale.GetText ("Invalid data."));
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 ();
243 private static RSA GetKey (DataProtectionScope scope)
246 case DataProtectionScope.CurrentUser:
249 CspParameters csp = new CspParameters ();
250 csp.KeyContainerName = "DAPI";
251 user = new RSACryptoServiceProvider (1536, csp);
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);
266 throw new CryptographicException (Locale.GetText ("Invalid scope."));