3

Attempting to use the kernel32 function SecureZeroMemory, using the code below, fails, with System.EntryPointNotFoundException - even though it is well documented here, on PInvoke, and here, on SO. Running completely normal Windows 10 Pro, on target .NET Framework 4.7.2.

        /// <summary>
        /// A kernel32 function that destroys all values in a block of memory
        /// </summary>
        /// <param name="destination">The pointer to the start of the block to be zeroed</param>
        /// <param name="length">The number of bytes to zero</param>
        /// <returns></returns>
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, EntryPoint = "RtlSecureZeroMemory")]
        public static extern void SecureZeroMemory(IntPtr destination, IntPtr length);
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
John
  • 598
  • 2
  • 7
  • 22
  • what kind of .net app are you writing? – Daniel A. White Nov 09 '18 at 19:54
  • WPF app, so windows only – John Nov 09 '18 at 20:14
  • It is not possible, since RtlSecureZeroMemory is not a function exported by a system DLL. It is rather a function **inlined** in winnt.h Essentially, when including winnt.h in a C/C++ project, the code of this function is becoming part of the code being complied. Now, obviously, you can't inline a C header file with C code in C#... :-( –  Nov 09 '18 at 20:26
  • So these people who've documented it must've just guessed. Would the best way to `__declspec(dllexport)` a wrapper to it in a C++ DLL? – John Nov 09 '18 at 20:28
  • Yeah, you could do that. –  Nov 09 '18 at 20:36

1 Answers1

2

This function is documented, but neither of the links that you include are the documentation. To understand what is going on, you should start by reading the actual documentation which is here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366877(v=vs.85).aspx

It says:

This function is defined as the RtlSecureZeroMemory function (see WinBase.h). The implementation of RtlSecureZeroMemory is provided inline and can be used on any version of Windows (see WinNT.h.)

What is meant by "provided inline" is that the function is defined in the header files and not exported by any system DLL. Which means that it cannot be called by p/invoke.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Thanks! I'll try and write a C++ wrapper around it to make it work. :) – John Nov 09 '18 at 21:16
  • Why, all it does is zeroise the memory, making sure that the code cannot be optimised out. Surely that can be done in pure C#. Use calls to `Marshal.Copy` to force zero bytes into unmanaged memory. Why are you even doing this in the first place? – David Heffernan Nov 09 '18 at 21:18
  • This project I'm doing is primarily for experience, so I could just use Array.Clear(), but I was curious about using [DllImport] so gave it a shot – John Nov 09 '18 at 21:21