Delphi - MadCrypt - string encryption and decryption problem
I am trying to encrypt a string, but often only part of the string is encrypted. I don't see anyone else having this problem, so I am probably doing something wrong. I have the same problem in Delphi 2007 and 2009. I am using Win XP SP3. Here is the code:
procedure TForm1.Button1Click(Sender: TObject);
var
sTestToConvert: ansistring;
sPassword: ansistring;
begin
sTestToConvert := trim(Memo1.Text);
sPassword := trim(Edit1.Text);
madCrypt.Encrypt(sTestToConvert, sPassword);
Memo2.Text := sTestToConvert;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
sTextToConvert: ansistring;
sPassword: ansistring;
begin
sPassword := trim(Edit1.Text);
sTextToConvert := trim(memo2.Text);
madCrypt.Decrypt(sTextToConvert, sPassword);
Memo1.Text := sTextToConvert;
end;
I also have the same problem when trying to use OldEncrypt and OldDecrypt. Any ideas on what is causing the problem? Thanks.
a source to share
I'm not sure what you mean when you say "only part of the string is encrypted". Do you mean that you can still see some text in sTestToConvert
even after the call Encrypt
?
Most likely what I expect you mean is that when you call Decrypt
, you only return a portion of the original string.
This is because it Encrypt
can store any byte value in the result, including non-printable characters, even a #0
null character. When you store such a string in TMemo
or TEdit
, the main Windows control treats the character #0
as the end of the line. It does not store the rest of the encrypted value. This way, when you call Decrypt
on what's stored in the edit control, you're only decrypting a portion of what you originally had.
If you want to have a text version of the encrypted data, use the functions Encode
and Decode
; the online documentation mentions this. They use base-64 encoding.
procedure TForm1.Button1Click(Sender: TObject);
var
sTestToConvert: AnsiString;
sPassword: AnsiString;
begin
sTestToConvert := Trim(Memo1.Text);
sPassword := Trim(Edit1.Text);
madCrypt.Encrypt(sTestToConvert, sPassword);
Memo2.Text := madCryt.Encode(sTestToConvert);
end;
procedure TForm1.Button2Click(Sender: TObject);
var
sTextToConvert: AnsiString;
sPassword: AnsiString;
begin
sPassword := Trim(Edit1.Text);
sTextToConvert := madCrypt.Decode(Memo2.Text);
madCrypt.Decrypt(sTextToConvert, sPassword);
Memo1.Text := sTextToConvert;
end;
a source to share