The following Delphi routine is originally from a long-ago CompuServe posting, and is used to encrypt various information in our database. Below are both the Delphi 2007 and (thanks to some SO help with the Unicode differences) Delphi XE versions.
We have been trying to convert this to C#, and have gotten close-ish, but we’re missing something somewhere. Unfortunately, our Delphi guy (me) doesn’t know C#, and the C# guy is new to Delphi. C# doesn’t (appear to) have the concept of AnsiString, so the solution will probably involve byte or char arrays?
We’d greatly appreciate any help in converting this to C#.
Delphi 2007 Version (ASCII)
function EncodeDecode(Str: string): string;
const
Hash: string = '^%12hDVjED1~~#29afdmSD`6ZvUY@hbkDBC3fn7Y7euF|R7934093*7a-|- Q`';
var
I: Integer;
begin
for I := 1 to Length (Str) do
Str[I] := chr (ord (Str[I]) xor not (ord (Hash[I mod Length (Hash) + 1])));
Result := Str;
end;
Delphi XE Version (Unicode)
function TfrmMain.EncodeDecode(Str: AnsiString): AnsiString;
const
Hash: string = '^%12hDVjED1~~#29afdmSD`6ZvUY@hbkDBC3fn7Y7euF|R7934093*7a-|- Q`';
var
I: Integer;
begin
Result := Str;
for I := 1 to Length (Result) do
Result[I] := AnsiChar (ord (Result[I]) xor not (Ord (Hash[I mod Length (Hash) + 1])));
end;
I don’t know C# either, so this is probably seriously non-idiomatic.
I have assumed that your ANSI strings are encoded with Windows 1252, but it you happen to have encoded your legacy data with a different code page it is obvious enough how to change it.
Since C# doesn’t have the equivalent of Delphi’s 8 bit string types, I personally would be sorely tempted to use
byte[]rather thanstring.Done that way it looks like this:
@Groo makes the excellent point that the hash can be initialised more cleanly list this: