Delphi字符串加密解密算法

unit Unit1;

interface

uses
  System.SysUtils;

const
  DefaultKey = 'delphi';

//==============================================================================
// 通过密钥加密解密
// 对字符串加密(Source:源 Key:密匙)
//==============================================================================

function EncryptString(Source: string; Key: string = DefaultKey): string;

function UnEncryptString(Source: string; Key: string = DefaultKey): string;

implementation

function EncryptString(Source: string; Key: string = DefaultKey): 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 := DefaultKey;
  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 UnEncryptString(Source: string; Key: string = DefaultKey): 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 := DefaultKey;
  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;

end.

 

posted on 2016-06-12 15:51  CookieDragon  阅读(763)  评论(0编辑  收藏  举报

导航