Delphi: how to completely delete a string from memory

Var S1:String; S2:String; begin S1:='Sensitive Data'; S2:=Crypt(S1,'encryption key'); S1:=''; FreeAndNil(S1); end; 

Now, when I look at my process memory using programs such as "WinHex", I can easily find an unencrypted string! even I tried to create a new form to encrypt this line and then upload the form, but it still exists

is there any way to completely remove it

early

+6
source share
2 answers

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 optimizes ZeroMemory, then you can use SecureZeroMemory. However, the Delphi compiler will not optimize far ZeroMemory so it is somewhat controversial.

If you just write:

 s := ''; 

then the memory will be returned as well as the memory manager. Then you cannot control when, if ever, the memory manager reuses or returns memory.

Obviously, you will need to do this with all copies of the string, and therefore the only sensible approach is not to create copies of the confidential data.

None of this will help with the code according to your question, because your sensitive data is a string literal and therefore is stored in an executable file. This approach can only be applied to dynamic data. I believe your real program does not put sensitive data in literals.

Oh, and never pass the string to FreeAndNil. You can only pass object variables to FreeAndNil, but the untyped var parameter is used in this procedure, so the compiler cannot save you from your error.

+5
source
 Var S1:String; S2:String; begin S1:='Sensitive Data'; S2:=Crypt(S1,'encryption key'); UniqueString(S1); // <-- if reference count of S1 is not 1 ZeroMemory(Pointer(S1), Length(S1)*SizeOf(Char)); // or better: SecureZeroMemory(Pointer(S1), Length(S1)*SizeOf(Char)); S1:=''; end; 
+3
source

Source: https://habr.com/ru/post/959488/


All Articles