Hi,
I made a Unit for the TFileStreams - Encrypt / Decrypt routines:
Encrypt
Code: Select all
procedure TCrypto.Encrypt(Stream: TStream; OutFile: TStream);
Var
Dest : TMemoryStream;
begin
try
Stream.Seek(0,soFromBeginning);
Dest := TMemoryStream.Create(OutFile);
Cipher.InitStr(Password,TDCP_sha512); // initialize the cipher with a hash of the passphrase
Cipher.EncryptStream(Stream,Dest,Stream.Size); // encrypt the contents of the file
Stream.Seek(0,soFromBeginning);
Cipher.Burn;
Dest.Free;
except
Raise CryptoException.CreateFmt('Cannot create file ''%s''.',[OutFile] );
end;
end;
Decrypt
Code: Select all
procedure TCrypto.Decrypt(Stream: TStream; InFile: String);
Var
Source : TFileStream;
begin
try
Source := TFileStream.Create(InFile,fmOpenRead);
Source.Seek(0,soFromBeginning);
Cipher.InitStr(Password,TDCP_sha512); // initialize the cipher with a hash of the passphrase
Cipher.DecryptStream(Source,Stream,Source.Size); // encrypt the contents of the file
Stream.Seek(0,soFromBeginning);
Cipher.Burn;
Source.Free;
except
Raise CryptoException.CreateFmt('File ''%s'' not opened.',[InFile] );
end;
end;
I then use it like this:
Encrypt
Code: Select all
procedure TForm1.Save1Click(Sender: TObject);
Var
Stream : TMemoryStream;
begin
if SaveDialog1.Execute then
Stream := TMemoryStream.Create;
rve.SaveRTFToStream(stream,False);
Crypto.Password := '32AFDDDF603850AB04DCD4394B83B44773885E2D9642585F0012AD95A0FC20BEBC650B4067E061F2CE8A4AE4BA224300CEF92D0467B153A9FBB4C94E2BCEC9D4';
Crypto.Encrypt(Stream,SaveDialog1.FileName);
Stream.Free;
end;
Decrypt
Code: Select all
procedure TForm1.Open1Click(Sender: TObject);
Var
Stream : TMemoryStream;
begin
If OpenDialog1.Execute then
Begin
Stream := TMemoryStream.Create;
Crypto.Password := '32AFDDDF603850AB04DCD4394B83B44773885E2D9642585F0012AD95A0FC20BEBC650B4067E061F2CE8A4AE4BA224300CEF92D0467B153A9FBB4C94E2BCEC9D4';
Crypto.Decrypt(Stream,OpenDialog1.FileName);
rve.clear;
rve.LoadRTFFromStream(stream);
Stream.Free;
rve.Format;
end;
end;
This all works fine with RichViewEdit and keeps the formatting once it's been Decrypted, all images, Rich Text and everything is restored.
If I try this with TMemoryStreams, I just get rtf code back:
Code: Select all
{\rtf1\ansi\ansicpg0\uc1\deff0\deflang0\deflangfe0
I haven't posted all of the RTF code above, just a very small snippet because it's too big. I could post it if you like.
This is really confusing as to why I just can't Decrypt it back and keep (.rtf) formatting using TMemoryStreams.
I need to use TMemoryStreams because I would like to send the Encrypted Text through an email but then at the receiving end it needs to be Copied and Pasted back and then Decrypted. FileStreams are no good because it saves the encrypted content to a File, this would not be good for my program.
Do you know why this is happening? I have been trying to get this to work for a few months now! I am not a Professional Coder and learn as I go along.
Many thanks, and again thank you for your time
Chris