3
votes

I am converting an old project that was written in Delphi 7 to newest version (Delphi Tokyo), In the old code there is this function that scrambles and unscrambles text but when I read the scrambled text with the same program compiled in Delphi Tokyo it just produces garbage.

Does anyone here know why the same code behaves and gives different result compiled with different versions of Delphi ?

Here is the function :

function TForm2.EnDeCrypt(const Value : String) : String;
var
  CharIndex : integer;
begin
  Result := Value;
  for CharIndex := 1 to Length(Value) do
    Result[CharIndex] := chr(not(ord(Value[CharIndex])));
end; 
1
In D7 string is AnsiStrings, in Delphi Tokio it is UnicodeString. - ain
ok thanks ! Got it now :) - Yngvi Thor Johannsson
stackoverflow.com/q/8460037/62576 might be useful to you. :-) Start with what was new in Delphi 2009, as it's where the major differences began. - Ken White
Fundamental problem here is that you are mistaken in operating on text. Encryption operates on binary data. - David Heffernan

1 Answers

1
votes

Starting with Delphi 2009, the string type automatically maps to the Unicode compatible UnicodeString type. Before, it mapped to the AnsiString type.

You can use your routine unchanged by expliticely using AnsiString and AnsiChar.

function TForm2.EnDeCrypt(const Value : AnsiString) : AnsiString;
var
  CharIndex : integer;
begin
  Result := Value;
  for CharIndex := 1 to Length(Value) do
    Result[CharIndex] := AnsiChar(not(ord(Value[CharIndex])));
end; 

Note that this can cause unexpected results at runtime if the string passed to the function does contain unicode characters that cannot be mapped to the local ANSI character set.