字串加密解密方法

來源:互聯網
上載者:User
  

function Decrypt(Src: string; Key: string): string;
var
  KeyLen, KeyPos, Offset, SrcPos, SrcAsc, TmpSrcAsc: Integer;
  Dest: string;
begin
  KeyLen := Length(Key);
  if KeyLen = 0 then
    Key := cPasswordKey;
  KeyPos := 0;
  Offset := StrToInt('$' + Copy(Src, 1, 2));
  SrcPos := 3;
  while SrcPos < Length(Src) do
  begin
    SrcAsc := StrToInt('$' + Copy(Src, 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;
  end;
  Result := Dest;
end;

function Encrypt(Src: string; Key: string): string;
var
  KeyLen, KeyPos, Offset, SrcPos, SrcAsc: Integer;
  Dest: string;
begin
  KeyLen := Length(Key);
  if KeyLen = 0 then
    Key := cPasswordKey;
  KeyPos := 0;
  Randomize;
  Offset := Random(256);
  Dest := Format('%1.2x', [Offset]);
  for SrcPos := 1 to Length(Src) do
  begin
    SrcAsc := (Ord(Src[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;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.