3

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; 
Ken White
  • 123,280
  • 14
  • 225
  • 444

1 Answers1

1

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.

NineBerry
  • 26,306
  • 3
  • 62
  • 93
  • 3
    This isn't quite unchanged though, because you can be caught out by issues with code page, when converting to other string types. The correct approach is to recognise that encryption operates on binary data rather than text and use byte arrays. Once you do so then the entire problem disappears. – David Heffernan Sep 13 '18 at 12:28
  • 1
    Yes this is what I changed also :) But you also need to replace the chr function to AnsiChar in the last line : Result[CharIndex] := Ansichar(not(ord(Value[CharIndex]))); – Yngvi Thor Johannsson Sep 14 '18 at 12:54