works:programmer:delphi:encrypt-decrypt-string-delphi7

Delphi 7 простое шифрование строки

На StackOverflow нашел алгоритм, но он для более новых версий Delphi, так как у клиента Delphi 7 пришлось немного преобразовать написанное для ANSI строк.

Мой шифровальщик

  // Encryption keys (WORD aligned)
  const CKEY1 = 53761; CKEY2 = 32618;
 
  function EncryptStr(const S: String; Key: Word): String;
  var
    i      : Integer;
    buffer : array of Word;
  begin
    Result := '';
    SetLength(buffer, Length(S));
    for i := 0 to Length(s)-1 do begin
      buffer[i] := Word(S[i+1]) xor (Key shr 8);
      Key := (buffer[i] + Key) * CKEY1 + CKEY2;
    end;
    for i := 0 to Length(buffer)-1 do begin
      Result := Result + IntToHex(buffer[i], 2);
    end;
    SetLength(buffer, 0);
  end;
 
  function DecryptStr(const S: String; Key: Word): String;
  var
    temp  : String;
    tmpKey: Word;
    i     : Integer;
    RStr  : array of Char;
  begin
    Result := '';
    temp := UpperCase(S);
    SetLength(RStr, Length(S) div 2);
    i := 1;
    try
      while (i < Length(temp)) do begin
        RStr[i div 2] := Chr(StrToInt('$' + temp[i] + temp[i+1]));
        Inc(i, 2);
      end;
    except
      SetLength(RStr, 0);
      Exit;
    end;
    for i := 0 to Length(RStr)-1 do begin
      tmpKey := Word(RStr[i]);
      RStr[i] := Char(Ord(RStr[i]) xor (Key shr 8));
      Key := (tmpKey + Key) * CKEY1 + CKEY2;
    end;
    Result := String(RStr);
    SetLength(RStr, 0);
  end;

Оригинальный код автора с StackOverflow

Ссылка 6798188/delphi-simple-string-encryption

const CKEY1 = 53761;
      CKEY2 = 32618;
 
function EncryptStr(const S :WideString; Key: Word): String;
var   i          :Integer;
      RStr       :RawByteString;
      RStrB      :TBytes Absolute RStr;
begin
  Result:= '';
  RStr:= UTF8Encode(S);
  for i := 0 to Length(RStr)-1 do begin
    RStrB[i] := RStrB[i] xor (Key shr 8);
    Key := (RStrB[i] + Key) * CKEY1 + CKEY2;
  end;
  for i := 0 to Length(RStr)-1 do begin
    Result:= Result + IntToHex(RStrB[i], 2);
  end;
end;
 
function DecryptStr(const S: String; Key: Word): String;
var   i, tmpKey  :Integer;
      RStr       :RawByteString;
      RStrB      :TBytes Absolute RStr;
      tmpStr     :string;
begin
  tmpStr:= UpperCase(S);
  SetLength(RStr, Length(tmpStr) div 2);
  i:= 1;
  try
    while (i < Length(tmpStr)) do begin
      RStrB[i div 2]:= StrToInt('$' + tmpStr[i] + tmpStr[i+1]);
      Inc(i, 2);
    end;
  except
    Result:= '';
    Exit;
  end;
  for i := 0 to Length(RStr)-1 do begin
    tmpKey:= RStrB[i];
    RStrB[i] := RStrB[i] xor (Key shr 8);
    Key := (tmpKey + Key) * CKEY1 + CKEY2;
  end;
  Result:= UTF8Decode(RStr);
end;
works/programmer/delphi/encrypt-decrypt-string-delphi7.txt · Last modified: 2022/01/03 12:09 by Chugreev Eugene