internal static unsafe bool CryptProtectData(SafeBSTRHandle uncryptedBuffer, out SafeBSTRHandle cryptedBuffer) { byte *uncryptedBufferPtr = null; DATA_BLOB pDataOut = default(DATA_BLOB); try { uncryptedBuffer.AcquirePointer(ref uncryptedBufferPtr); DATA_BLOB pDataIn = new DATA_BLOB((IntPtr)uncryptedBufferPtr, uncryptedBuffer.Length * 2); if (CryptProtectData(new IntPtr(&pDataIn), String.Empty, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, CRYPTPROTECTMEMORY_SAME_PROCESS, new IntPtr(&pDataOut))) { SafeBSTRHandle newHandle = SafeBSTRHandle.Allocate(pDataOut.pbData, pDataOut.cbData); cryptedBuffer = newHandle; return(true); } else { cryptedBuffer = SafeBSTRHandle.Allocate(null, 0); return(false); } } finally { if (uncryptedBufferPtr != null) { uncryptedBuffer.ReleasePointer(); } if (pDataOut.pbData != IntPtr.Zero) { NtDll.ZeroMemory(pDataOut.pbData, (UIntPtr)pDataOut.cbData); Marshal.FreeHGlobal(pDataOut.pbData); } } }
internal static extern void ZeroMemory(SafeBSTRHandle address, uint length);
internal static extern bool CryptUnprotectMemory(SafeBSTRHandle pData, uint cbData, uint dwFlags);
internal static extern uint SysStringLen(SafeBSTRHandle bstr);