internal static byte[] ProtectData(byte[] data, string name, CryptProtectDataFlags dwFlags) { byte[] cipherText = null; // copy data into unmanaged memory DPAPI.DATA_BLOB din = new DPAPI.DATA_BLOB(); din.cbData = data.Length; din.pbData = Marshal.AllocHGlobal(din.cbData); if (din.pbData.Equals(IntPtr.Zero)) { throw new OutOfMemoryException("Unable to allocate memory for buffer."); } Marshal.Copy(data, 0, din.pbData, din.cbData); DPAPI.DATA_BLOB dout = new DPAPI.DATA_BLOB(); try { bool cryptoRetval = DPAPI.CryptProtectData(ref din, name, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, dwFlags, ref dout); if (cryptoRetval) { int startIndex = 0; cipherText = new byte[dout.cbData]; Marshal.Copy(dout.pbData, cipherText, startIndex, dout.cbData); DPAPI.LocalFree(dout.pbData); } else { int errCode = Marshal.GetLastWin32Error(); StringBuilder buffer = new StringBuilder(256); Win32Error.FormatMessage(Win32Error.FormatMessageFlags.FORMAT_MESSAGE_FROM_SYSTEM, IntPtr.Zero, errCode, 0, buffer, buffer.Capacity, IntPtr.Zero); } } finally { if (!din.pbData.Equals(IntPtr.Zero)) { Marshal.FreeHGlobal(din.pbData); } } return(cipherText); }