//加密关键字:key=“123”
//明码:1231adcd1234
//加密后,8FAF8FA7AC43E90F25151F0853
function TMainForm.EncryptString(Source, Key: string): string; //加密
var
KeyLen: integer;
KeyPos: integer;
Offset: integer;
Dest: string;
SrcPos: integer;
SrcAsc: integer;
Range: integer;
begin
KeyLen := Length(Key);
if KeyLen = 0 then
Key := 'delphi';
KeyPos := 0;
Range := 256;
randomize;
Offset := random(Range);
Dest := format('%1.2x', [Offset]);
for SrcPos := 1 to Length(Source) do
begin
SrcAsc := (Ord(Source[SrcPos]) + 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 TMainForm.UnEncryptString(Source, Key: string): string; //解密
var
KeyLen: integer;
KeyPos: integer;
Offset: integer;
Dest: string;
SrcPos: integer;
SrcAsc: integer;
TmpSrcAsc: integer;
begin
KeyLen := Length(Key);
if KeyLen = 0 then
Key := 'delphi';
KeyPos := 0;
Offset := strtoint('$' + copy(Source, 1, 2));
SrcPos := 3;
repeat
SrcAsc := strtoint('$' + copy(Source, SrcPos, 2));
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;
Dest := Dest + chr(TmpSrcAsc);
Offset := SrcAsc;
SrcPos := SrcPos + 2;
until SrcPos >= Length(Source);
result := Dest;
end;
//我用C语言写的解密算法不对?请帮忙检查,谢谢.....
char a2x( char ch )
{
switch( ch )
{
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'A':
case 'a':
return 10;
case 'B':
case 'b':
return 11;
case 'C':
case 'c':
return 12;
case 'D':
case 'd':
return 13;
case 'E':
case 'e':
return 14;
case 'F':
case 'f':
return 15;
default:
break;;
}
return 0;
}
void unEncrypt( char *source, int srcLen )
{
xdata char i = 0;
xdata char keyLen;
xdata char keyPos;
xdata char srcPos;
xdata char srcAsc;
xdata char tmpSrcAsc;
xdata char offset;
xdata char key[] = "123";
xdata char dest[64] = { 0, };
keyPos = 0;
keyLen = strlen( key );
offset = ( a2x( source[0] ) << 4 ) | a2x( source[1] );
for( srcPos = 2; srcPos < srcLen; )
{
srcAsc = ( a2x( source[srcPos] ) << 4 ) | a2x( source[srcPos + 1] );
tmpSrcAsc = srcAsc ^ key[keyPos];
if( tmpSrcAsc <= offset )
{
tmpSrcAsc = 255 + tmpSrcAsc - offset;
}
else
{
tmpSrcAsc = tmpSrcAsc - offset;
}
dest[i++] = tmpSrcAsc;
offset = srcAsc;
srcPos += 2;
if( keyPos < keyLen )
{
keyLen++;
}
else
{
keyPos = 0;
}
}
} |