带密匙的字符串加密解密函数(支持中文)
uses AnsiStrings;
Function JiaMi(Src:String; Key:String):String;
var
KeyLen :Integer;
KeyPos :Integer;
offset :Integer;
dest :String;
SrcPos :Integer;
SrcAsc :Integer;
Range :Integer;
IntTemp:integer;
SrcAnsi:PAnsiChar;
begin
KeyLen:=Length(Key);
KeyPos:=0;
Range:=1;
Randomize;
offset:=Random(Range);
dest:=format('%1.2x',[offset]);
SrcAnsi:=PAnsiChar(AnsiString(Src));
IntTemp:= Length(SrcAnsi);
for SrcPos := 1 to IntTemp do
begin
SrcAsc:=(Ord(SrcAnsi[SrcPos-1]) + offset) MOD 255;
if KeyPos < KeyLen then KeyPos:= KeyPos + 1 else KeyPos:=1;
SrcAsc:= SrcAsc xor Ord(Key[KeyPos]);
dest:=dest + format('%1.2x',[SrcAsc]);
offset:=SrcAsc;
end;
Result:=Dest;
end;
//解密函数
Function JieMi (Src:String; Key:String):String;
var
KeyLen :Integer;
KeyPos :Integer;
offset :Integer;
dest :String;
SrcPos :Integer;
SrcAsc :Integer;
TmpSrcAsc :Integer;
Range :Integer;
SrcAnsi:PAnsiChar;
IntTemp,i:Integer;
ByteArray: array of Byte;
begin
KeyLen:=Length(Key);
if KeyLen = 0 then key:='starlin';
KeyPos:=0;
SrcPos:=0;
SrcAsc:=0;
Range:=1;
offset:=StrToInt('$'+ copy(src,1,2));
SrcPos:=3;
IntTemp:=Length(Src) div 2;
setlength(ByteArray,IntTemp);
i:=0;
repeat
try
SrcAsc:=StrToInt('$'+ copy(src,SrcPos,2));
except
SrcAsc:=StrToInt('$00');
end;
if KeyPos < KeyLen Then KeyPos := KeyPos + 1 else KeyPos := 1;
TmpSrcAsc := SrcAsc xor Ord(Key[KeyPos]);
if TmpSrcAsc <= offset then
TmpSrcAsc := 255 + TmpSrcAsc - offset
else
TmpSrcAsc := TmpSrcAsc - offset;
ByteArray[i]:=TmpSrcAsc;
i:=i+1;
offset:=srcAsc;
SrcPos:=SrcPos + 2;
until SrcPos >= Length(Src);
CopyMemory(@SrcAnsi[0],@ByteArray[0],IntTemp);
dest:=string(AnsiStrings.strpas(SrcAnsi));
Result:=Dest;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
showmessage(jiami('www.delphitop.com','123'));
showmessage(jiemi(jiami('www.delphitop.com','123'),'123'));
end;