When you try to decrypt a file which is not encrypted or is encrypted with a different key the result, obviously, can
not be correct. You should try to determine whether a file is encrypted and, if so, ask the user for the key. A quick and dirty example:
resourcestring
sPassCaption = 'Need a password!';
sPassPrompt = 'File %s is encrypted; please supply the key';
procedure OpenFileInMemo(AMemo: TMemo; DontDecrypt: Boolean = False);
var
AFilename,
APassword: String;
begin
if OpenDialog.Execute then begin
AFilename := OpenDialog.Filename;
{ You'll have to build your own FileIsEncrypted() function!!! }
if DontDecrypt or (not FileIsEncrypted(AFilename)) then
AMemo.LoadFromFile(AFilename)
else begin
APassword := PasswordBox(sPassCaption,
Format(sPassPrompt, [ExtractFilename(AFilename)]);
AMemo.Text := LoadFromFileAndDecrypt(AFilename, APasword);
end;
end;
end;
Do note that this loads (and, if needed, decrypts) directly from a file to a TMemo. If, as it looks from your questions, you want to have two memos, one with the encrypted and one with the decrypted text you'll have to do something like:
function DecryptFromMemo(AMemo: TMemo; AKey: String): String;
var
de: TBlowFishDeCryptStream;
s1: TStringStream;
Value, temp: string;
begin
Result := 'error';
s1 := TStringStream.Create(AMemo.Text);
try
de := TBlowFishDecryptStream.Create(KeyPhrase, s1);
try
Result := de.ReadAnsiString;
finally
de.Free;
end;
finally
s1.Free;
end;
end;
Which you may then use from something like:
procedure LoadMemos;
var
APassword: String;
begin
if OpenDialog.Execute then begin
Memo2.LoadFromFile(OpenDialog.Filename);
APassword := PasswordBox('My kingdom for a key!', 'Have you got a key?');
if APassword <> '' then
Memo1.Text := DecryptFromMemo(Memo2, APassword)
else
ShowMessage('No password? No kingdom!');
end;
end;
Note that I typed all this directly and it's un-syntax-checked and untested, so there may be some (small) error(s); but it should be enough for you to get what I'm trying to show you.
HTH!