How can I apply a file encryption/decryption mechanism correctly in Delphi?
I found a very old source that supposedly teaches how to do just that, but using strings. After my previous question here, that doesn't appear to be the correct approach. Rather I should perform byte operations. This is what my old source proposes:
1-) Read the file using the old binded C function:
function ReadFile(path: String): AnsiString;
var
file: File;
type: Byte;
begin
type:= FileMode;
try
FileMode := 0;
AssignFile(file, path);
{$I-}
Reset(file, 1);
{$I+}
if IOResult = 0 then
try
SetLength(Result, FileSize(file));
if Length(Result) > 0 then
begin
{$I-}
BlockRead(file, Result[1], Length(Result));
{$I+}
if IOResult <> 0 then
Result := '';
end;
finally
CloseFile(file);
end;
finally
FileMode := type;
end;
end;
2-) Apply the XOR operations character by character on this huge AnsiString, like so:
function Xor(Buffer: String; Key: integer): String;
var
i, c, x: integer;
begin
for i := 1 to Length(Buffer) do
begin
c := integer(Buffer[i]);
x := c xor Key;
Result := Result + Char(x);
end;
end;
But the problem afterwards, and is what my source does NOT show, is how to convert this transformed string back to bytes so I can have a functional resource to write back to a new decrypted file.
Apparently this is not the correct approach to encrypt and decrypt a file. Can someone please explain to me the correct approach to properly:
Read a file, apply a basic XOR encryption mechanism and then be able to read this file again, decrypt it and use this VALID binary (DLL, EXE) data to write back into a new decrypted file?
A "simple xor encryption" will not improve security of an application. Make sure to add a comment informing any reader that this performs no security benefit, as it might confuse another developer into thinking that it raises the bar against an attacker. If this was a security system then you would need to use AES for encryption or SHA-256/SHA3 for hashing, or PBKDF2/Scrypt for password storage.
That being said, GitHub search is powerful, here is some delphi code that obfuscates bits: https://github.com/EonaCat/NightBitsEncryptor/blob/master/NightBitsEncryptor.pas
The above code is (in)security though obscurity and must never be used as a security system.