Using SecureZeroMemory in Delphi

2019-06-24 07:05发布

问题:

I understand there is a SecureZeroMemory function in C. The function implementation is defined in <WinnNT.h> as RtlSecureZeroMemory function.

QNS: How can SecureZeroMemory be used in Delphi? Did Delphi release a library that contains that function? I'm using Delphi 7. Windows.pas only has ZeroMemory but not SecureZeroMemory.

回答1:

As far as I understand, the only difference between ZeroMemory and SecureZeroMemory is SecureZeroMemory is implemented as an inline function, ensuring it won't be optimised out by the compiler.

I don't think Delphi performs the same level of compiler optimisation, so ZeroMemory calls shouldn't be optimised out.



回答2:

Since according to MSDN, SecureZeroMemory() is actually defined as the RtlSecureZeroMemory(), you can declare SecureZeroMemory() as follows:

  procedure SecureZeroMemory(_ptr: Pointer; cnt: Longint); external 'kernel32.dll' name 'RtlSecureZeroMemory';

SecureZeroMemory() is merely an alias of RtlSecureZeroMemory().



回答3:

I do not have a Delphi compiler available right now, but I do not think there is a need for SecureZeroMemory.

I do remember that in Delphi, the Win32 API functions/macros CopyMemory and MoveMemory are identical (they are both implemented just as the pointer "versions" of the Move RTL function). Hence, the remark at the MSDN CopyMemory reference page saying that you must use MoveMemory rather than CopyMemory is the blocks overlap, is irrelevant. Delphi's Move always makes the right thing.

I think the same thing applies to ZeroMemory and SecureZeroMemory. The first is implemented as FillChar with #0, and if there would be a SecureZeroMemory function for Deplhi, I think it would also just be a FillChar with #0. (If FillChar would be ignored at some times, it really should be documented in the Delphi reference, but it isn't.)

Please correct me if I am wrong!



回答4:

Take a look at the MSDN help here.

The only question whether Delphi's compiler removes ZeroMemory as an optimization result, athough i doubt that.