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
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With