I am trying to implement a simple text file encryption technique and I am using the following code to do so. The code is not written by me, I just googled and got it. The encryption technique seems to be pretty simple, concise and easy to implement. I see that it has only one function that can do the encryption and the decryption on the fly. Just pass the key it will do the trick. However, I just wanted to know, is it possible for me to check if the key is passed by the user is correct or not. Currently it will just encrypt / decrypt the text file based on the passed key. But there is no mechanism to check if we are decrypting with correct key or not. Whatever the key we pass, it will get decrypted, but it will not be readable. Any idea how to tackle this problem..?
procedure TEnDeCrypt.EnDecryptFile(pathin, pathout: string; Chave: Word);
var
InMS, OutMS: TMemoryStream;
cnt: Integer;
C: byte;
begin
InMS := TMemoryStream.Create;
OutMS := TMemoryStream.Create;
try
InMS.LoadFromFile(pathin);
InMS.Position := 0;
for cnt := 0 to InMS.Size - 1 DO
begin
InMS.Read(C, 1);
C := (C xor not (ord(chave shr cnt)));
OutMS.Write(C, 1);
end;
OutMS.SaveToFile(pathout);
finally
InMS.Free;
OutMS.Free;
end;
end;