[fpc-pascal] Saving and reading TBlowfish crypted text

Antonio Sanguigni a.sanguigni at gmail.com
Mon Mar 16 21:05:39 CET 2015


Hi all,

I need to encrypt TMemo.Lines and to write it to a file. Then, of
course, I need the contrary operation I mean reading encrypted text on
file, decrypt it to put into TMemo.Lines.

Reading the Net I found lots of example code.

Now, I'm able to to crypt and decrypt from stream, I'm able to write
and read TMemo plain text on a text file. My real difficult is to read
from crypted (I hope it is right) file to decrypt into a TMemo. I got
a TReadError on de.ReadAnsiString.

Here is my example code (please, nevermind about memory lacks and
dirty code, it is just a test).

Thanks in advance for any help.

Antonio

//------------ Crypt and write -----------
procedure TForm1.Button1Click(Sender: TObject);
var fs: TFileStream;
  tfOut: TextFile;
begin
  fs := TFileStream.Create('textfile.txt', fmCreate);
  fs.Seek(0,soBeginning);
  { 1 }
   key := 'testkey';
   { 2 }
   s1 := TStringStream.Create('');
   en := TBlowFishEncryptStream.Create(key,s1);
   { 3 }
   en.WriteAnsiString(Memo1.Lines.Text);
   fs.WriteBuffer(Pointer(s1.DataString)^, length(s1.DataString));
   en.Free;

  fs.Free;
end;

//----------------Read and decrypt ------------------
procedure TForm1.Button2Click(Sender: TObject);
var
tr : string;
fs : TFileStream;
tfOut: TextFile;
Begin
   Fs := TFileStream.Create('textfile.txt', fmOpenRead or fmShareDenyNone);
   SetLength(tr, Fs.Size);
   Fs.ReadBuffer(tr[1], Fs.Size);
   key := 'testkey';
   s2 := TStringStream.Create(tr);
//   s1.Free;
   de := TBlowFishDeCryptStream.Create(key,s2);
  { 6 }
  temp := de.ReadAnsiString; // TEReadError exception
  WriteLn('decrypted: ' + temp);
  Memo1.Lines.Text := temp;

  de.Free;
  s2.Free;
end;



-- 
Antonio Sanguigni alias slapshot
----------------------------------------------------------------------
Servizi informatici Windows e GNU/Linux- http://www.pieroni.biz
GioveLUG (Linux User Group) - http://www.giovelug.org



More information about the fpc-pascal mailing list