You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 6 Next »

There are lots of way can encrypt a text string based on a key. By the approach, you can use a single numerical key, or text string. In terms of security's point of view, text string-based key has better security performance.

function Encrypt(const InString:string; Salt:string): string;
var
i : Byte;
StartKey, MultKey, AddKey: Word;
begin
Result := '';
if (Salt = '') then begin
Result := InString;
end
else begin
StartKey := Length(Salt);
MultKey := Ord(Salt[1]);
AddKey := 0;
for i := 1 to Length(Salt) - 1 do AddKey := AddKey + Ord(Salt[i]);
for i := 1 to Length(InString) do
begin
Result := Result + CHAR(Byte(InString[i]) xor (StartKey shr 8));
StartKey := (Byte(Result[i]) + StartKey) * MultKey + AddKey;
end;
end;
end;

function Decrypt(const InString:string; Salt:string): string;
var
i : Byte;
StartKey, MultKey, AddKey: Word;
begin
Result := '';
if (Salt = '') then begin
Result := InString;
end
else begin
StartKey := Ord(Salt[1]);
MultKey := Length(Salt);
AddKey := 0;
for i := 1 to Length(Salt) - 1 do AddKey := AddKey + Ord(Salt[i]);
for i := 1 to Length(InString) do
begin
Result := Result + CHAR(Byte(InString[i]) xor (StartKey shr 8));
StartKey := (Byte(InString[i]) + StartKey) * MultKey + AddKey;
end;
end;
end;

Example

procedure TForm1.btn1Click(Sender: TObject);
begin
  txt2.Text:= EncryptStr(txt1.Text, 223);
  lbl1.Caption:= DecryptStr(txt2.Text, 223);
end;

Below example is using a text string-based key to encrypt text string.


  • No labels