Delphi : how to completely remove String from the memory

delphi, encryption, memory, string

Solution

You need to overwrite the string with zeros when you are done with it. Like this:

ZeroMemory(Pointer(s), Length(s)*SizeOf(Char));

If you are paranoid that the compiler will optimise away the ZeroMemory then you could use SecureZeroMemory. However, the Delphi compiler will not optimise away ZeroMemory so this is somewhat moot.

If you just write:

s := '';

then the memory will be returned as is to the memory manager. You then have no control over when, if ever, the memory manager re-uses or returns the memory.

Obviously you'd need to do that to all copies of the string, and so the only sane approach is not to make copies of sensitive data.

None of this will help with the code as per your question because your sensitive data is a string literal and so is stored in the executable. This approach can only be applied meaningfully for dynamic data. I presume that your real program does not put sensitive data in literals.

Oh, and don't ever pass a string to FreeAndNil. You can only pass object variables to FreeAndNil, but the procedure uses an untyped var parameter so the compiler cannot save you from your mistake.

Problem

``` Var S1:String; S2:String; begin S1:='Sensitive Data'; S2:=Crypt(S1,'encryption key'); S1:=''; FreeAndNil(S1); end; ``` now when i search on my process memory using programs like "WinHex" i can easly find the un-crypted String ! even i tried to make new form to encrypt this string then unload the form but it still exist is there any way to completely remove it thanks in advance

Original source

Related problems