简体   繁体   中英

How do I modify my Char based encryption code to work with Unicode Delphi?

I'm stuck trying to make some legacy Delphi 2007 code work in Delphi XE2.

Function EncryptionWithPassword(Str,Pwd: AnsiString; Encode: Boolean): AnsiString;
var
  a,PwdChk,Direction,ShiftVal,PasswordDigit : Integer;
begin
  PasswordDigit := 1;
  PwdChk := 0;
  for a := 1 to Length(Pwd) do Inc(PwdChk,Ord(Pwd[a]));
  Result := PChar(Str);
  If Encode then Direction := -1 else Direction := 1;
  for a := 1 to Length(Result) do
    begin
      if Length(Pwd)=0 then
        ShiftVal := a
      else
        ShiftVal := Ord(Pwd[PasswordDigit]);
      if Odd(A) then
        Result[A] := RotateBits(Result[A],-Direction*(ShiftVal+PwdChk))
      else
        Result[A] := RotateBits(Result[A],Direction*(ShiftVal+PwdChk));
      inc(PasswordDigit);
      if PasswordDigit > Length(Pwd) then PasswordDigit := 1;
    end;

end;

Function RotateBits(C: Char; Bits: Integer): Char;
var
  SI : Word; 
begin 
  Bits := Bits mod 8; 
  // Are we shifting left? 
  if Bits < 0 then 
    begin 
      // Put the data on the right half of a Word (2 bytes) 
      SI := MakeWord(Byte(C),0); 
      // Now shift it left the appropriate number of bits 
      SI := SI shl Abs(Bits);
    end
  else
    begin
      // Put the data on the left half of a Word (2 bytes)
      SI := MakeWord(0,Byte(C));
      // Now shift it right the appropriate number of bits
      SI := SI shr Abs(Bits);
    end;
  // Now OR the two halves together
  SI := Lo(SI) or Hi(SI);
  Result := Chr(SI);
end;

No matter what I try - the function corrupts the string. After I've applied the AnsiString cheat, I've tried using arrays of chars, etc, nothing works. Please if anyone with some insight can assist and explain - I'm at my wits end and is delaying a huge project.

只需将Char更改为AnsiChar,一切都会正常。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM