如何修改基于字符的加密代码以使用Unicode Delphi?

如何修改基于字符的加密代码以使用Unicode Delphi?,delphi,unicode,Delphi,Unicode,我一直在尝试用DelphiXe2编写一些遗留的Delphi2007代码 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) d

我一直在尝试用DelphiXe2编写一些遗留的Delphi2007代码

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;

无论我尝试什么,函数都会破坏字符串。在我应用了AnsiString欺骗之后,我尝试了使用字符数组等,但没有任何效果。如果有人有一些见解,请提供帮助和解释-我束手无策,正在推迟一个大型项目。

只要将Char更改为AnsiChar,一切都应该正常。

这是什么代码?此代码是否符合D2007的要求?或者这是你在港口的企图?程序的预期输出是什么。它是如何失败的。两者都是-这是我尝试的端口,但它在D2007中工作,但在转换时会损坏字符串。它基于web上的一个示例,现在只能在此处找到:。EncryptionWithPassword使用RotateBits。您读过Unicode更改吗?只是炭的使用让人觉得很难受。我真的建议你花点时间看看马可的白皮书。这将帮助您更快地完成端口。谢谢@TLama!!介意贴出来吗?这样我就可以把它标记为答案了?我已经在上面实现了Nick的建议,但没有实现PAnsiChar。加密的第一条规则是,将所有内容都视为字节。远离字符串表示。查看我关于这个主题的旧帖子:我只是在需要字符串的非关键内容上使用它。伙计,Hein,你没有阅读delphi世界上所有的Unicode转换文档吗?unicode delphi中的字符大小超过1字节。说真的。@WarrenP当然,我把所有的字符都转换成了AnsiChars,把字符串转换成Ansistring,但我没有意识到有一个PAnsiChar,所以我可能没有在40页的白皮书中读到足够的内容:/