views:

460

answers:

1

I am trying to encrypt a string but often only part of the string is being 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.

+5  A: 

I'm not sure what you mean when you say "only part of the string is being encrypted." Do you mean that you can still see some of the plaintext in sTestToConvert even after calling Encrypt?

More likely, I expect you mean that when you call Decrypt, you only get part of the original string back.

That's because Encrypt may store any byte value in the result, including non-printing characters, even #0, the null character. When you store such a string in a TMemo or TEdit, the underlying Windows control treats the #0 character as the end of the string. It doesn't store the rest of the encrypted value. Thus, when you call Decrypt on what's stored in the edit control, you are only decrypting a portion of what you originally had.

If you want to have a text version of the encrypted data, use the Encode and Decode functions; the documentation online mentions this. Those 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;
Rob Kennedy
Thanks Rob...that was the problem and it is now working. I appreciate the help.
C Harmon