(*//
标题:字符串加密;pascal字符表示
说明:应用于文件加密
设计:Zswang
日期:2002-02-19
支持:wjhu111@21cn.com
//*)
///////Begin Source
function StringToDisplay(mString: string): string;
var
I: Integer;
S: string;
begin
Result := '';
S := '';
for I := 1 to Length(mString) do
if mString[I] in [#32..#127] then
S := S + mString[I]
else begin
if S <> '' then begin
Result := Result + QuotedStr(S);
S := '';
end;
Result := Result + Format('#$%x', [Ord(mString[I])]);
end;
if S <> '' then Result := Result + QuotedStr(S);
end; { StringToDisplay }
function DisplayToString(mDisplay: string): string;
var
I: Integer;
S: string;
B: Boolean;
begin
Result := '';
B := False;
mDisplay := mDisplay;
for I := 1 to Length(mDisplay) do
if B then case mDisplay[I] of
'''': begin
if S <> '' then Result := Result + StringReplace(S, '''''', '''', [rfReplaceAll]);
if Copy(mDisplay, I + 1, 1) = '''' then Result := Result + '''';
S := '';
B := False;
end;
else S := S + mDisplay[I];
end
else case mDisplay[I] of
'#', '''': begin
if S <> '' then Result := Result + Chr(StrToIntDef(S, 0));
S := '';
B := mDisplay[I] = '''';
end;
'$', '0'..'9', 'a'..'f', 'A'..'F': S := S + mDisplay[I];
end;
if (not B) and (S <> '') then Result := Result + Chr(StrToIntDef(S, 0));
end; { DisplayToString }
function StringEncrypt(mStr: string; mKey: string): string;
var
I, J: Integer;
begin
J := 1;
Result := '';
for I := 1 to Length(mStr) do begin
Result := Result + Char(Ord(mStr[I]) xor Ord(mKey[J]));
if J + 1 <= Length(mKey) then
Inc(J)
else J := 1;
end;
{ 自己加步骤 }
end; { StringEncrypt }
function StringDecrypt(mStr: string; mKey: string): string;
var
I, J: Integer;
begin
J := 1;
Result := '';
{ 自己加步骤 }
for I := 1 to Length(mStr) do begin
Result := Result + Char(Ord(mStr[I]) xor Ord(mKey[J]));
if J + 1 <= Length(mKey) then
Inc(J)
else J := 1;
end;
end; { StringDecrypt }
///////End Source
///////Begin Demo
const
cKey = '给你这一把钥匙,只能打开这一把锁';
procedure TForm1.Button1Click(Sender: TObject);
begin
Memo2.Text := StringToDisplay(StringEncrypt(Memo1.Text, cKey));
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Memo1.Text := StringDecrypt(DisplayToString(Memo2.Text), cKey);
end;
///////End Demo