2 // NativeDapiProtection.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.
33 using System.Runtime.InteropServices;
34 using System.Security;
35 using System.Security.Cryptography;
36 using System.Security.Permissions;
38 namespace Mono.Security.Cryptography {
40 // DAPI is only available in Windows 2000 and later operating systems
41 // see ManagedProtection for other platforms
44 // * no need to assert KeyContainerPermission here as unmanaged code can
46 // * which is why we also need the [SuppressUnmanagedCodeSecurity]
47 // attribute on each native function (so we don't require UnmanagedCode)
49 internal class NativeDapiProtection {
51 private const uint CRYPTPROTECT_UI_FORBIDDEN = 0x1;
52 private const uint CRYPTPROTECT_LOCAL_MACHINE = 0x4;
54 [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Auto)]
55 private struct DATA_BLOB {
58 private IntPtr pbData;
60 public void Alloc (int size)
63 pbData = Marshal.AllocHGlobal (size);
68 public void Alloc (byte[] managedMemory)
70 if (managedMemory != null) {
71 int size = managedMemory.Length;
72 pbData = Marshal.AllocHGlobal (size);
74 Marshal.Copy (managedMemory, 0, pbData, cbData);
80 if (pbData != IntPtr.Zero) {
81 // clear copied memory!
82 ZeroMemory (pbData, cbData);
83 Marshal.FreeHGlobal (pbData);
89 public byte[] ToBytes ()
94 byte[] managedMemory = new byte[cbData];
95 Marshal.Copy (pbData, managedMemory, 0, cbData);
100 [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Auto)]
101 private struct CRYPTPROTECT_PROMPTSTRUCT {
104 private uint dwPromptFlags;
105 private IntPtr hwndApp;
106 private string szPrompt;
108 public CRYPTPROTECT_PROMPTSTRUCT (uint flags)
110 cbSize = Marshal.SizeOf (typeof (CRYPTPROTECT_PROMPTSTRUCT));
111 dwPromptFlags = flags;
112 hwndApp = IntPtr.Zero;
117 // http://msdn.microsoft.com/library/en-us/seccrypto/security/cryptprotectdata.asp
118 [SuppressUnmanagedCodeSecurity]
119 [DllImport ("crypt32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
120 private static extern bool CryptProtectData (ref DATA_BLOB pDataIn, string szDataDescr, ref DATA_BLOB pOptionalEntropy,
121 IntPtr pvReserved, ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct, uint dwFlags, ref DATA_BLOB pDataOut);
123 // http://msdn.microsoft.com/library/en-us/seccrypto/security/cryptunprotectdata.asp
124 [SuppressUnmanagedCodeSecurity]
125 [DllImport ("crypt32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
126 private static extern bool CryptUnprotectData (ref DATA_BLOB pDataIn, string szDataDescr, ref DATA_BLOB pOptionalEntropy,
127 IntPtr pvReserved, ref CRYPTPROTECT_PROMPTSTRUCT pPromptStruct, uint dwFlags, ref DATA_BLOB pDataOut);
129 // http://msdn.microsoft.com/library/en-us/memory/base/zeromemory.asp
130 // note: SecureZeroMemory is an inline function (and can't be used here)
131 // anyway I don't think the CLR will optimize this call away (like a C/C++ compiler could do)
132 [SuppressUnmanagedCodeSecurity]
133 [DllImport ("kernel32.dll", EntryPoint = "RtlZeroMemory", SetLastError = false, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
134 private static extern void ZeroMemory (IntPtr dest, int size);
139 public static byte[] Protect (byte[] userData, byte[] optionalEntropy, DataProtectionScope scope)
141 byte[] encdata = null;
144 DATA_BLOB data = new DATA_BLOB ();
145 DATA_BLOB entropy = new DATA_BLOB ();
146 DATA_BLOB cipher = new DATA_BLOB ();
148 CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT (0);
149 data.Alloc (userData);
150 entropy.Alloc (optionalEntropy);
152 // note: the scope/flags has already been check by the public caller
153 uint flags = CRYPTPROTECT_UI_FORBIDDEN;
154 if (scope == DataProtectionScope.LocalMachine)
155 flags |= CRYPTPROTECT_LOCAL_MACHINE;
157 // note: on Windows 2000 the string parameter *cannot* be null
158 if (CryptProtectData (ref data, String.Empty, ref entropy, IntPtr.Zero,
159 ref prompt, flags, ref cipher)) {
160 // copy encrypted data back to managed codde
161 encdata = cipher.ToBytes ();
163 hr = Marshal.GetLastWin32Error ();
166 catch (Exception ex) {
167 string msg = Locale.GetText ("Error protecting data.");
168 throw new CryptographicException (msg, ex);
176 if ((encdata == null) || (hr != 0)) {
177 throw new CryptographicException (hr);
182 public static byte[] Unprotect (byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope)
184 byte[] decdata = null;
187 DATA_BLOB cipher = new DATA_BLOB ();
188 DATA_BLOB entropy = new DATA_BLOB ();
189 DATA_BLOB data = new DATA_BLOB ();
191 CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT (0);
192 cipher.Alloc (encryptedData);
193 entropy.Alloc (optionalEntropy);
195 // note: the scope/flags has already been check by the public caller
196 uint flags = CRYPTPROTECT_UI_FORBIDDEN;
197 if (scope == DataProtectionScope.LocalMachine)
198 flags |= CRYPTPROTECT_LOCAL_MACHINE;
200 if (CryptUnprotectData (ref cipher, null, ref entropy, IntPtr.Zero,
201 ref prompt, flags, ref data)) {
202 // copy decrypted data back to managed codde
203 decdata = data.ToBytes ();
205 hr = Marshal.GetLastWin32Error ();
208 catch (Exception ex) {
209 string msg = Locale.GetText ("Error protecting data.");
210 throw new CryptographicException (msg, ex);
218 if ((decdata == null) || (hr != 0)) {
219 throw new CryptographicException (hr);