How can I convert this XOR-encryption function from Delphi to C#? -
the following delphi routine long-ago compuserve posting, , used encrypt various information in our database. below both delphi 2007 , (thanks unicode differences) delphi xe versions.
we have been trying convert c#, , have gotten close-ish, we're missing somewhere. unfortunately, our delphi guy (me) doesn't know c#, , c# guy new delphi. c# doesn't (appear to) have concept of ansistring, solution involve byte or char arrays?
we'd appreciate in converting c#.
delphi 2007 version (ascii)
function encodedecode(str: string): string; const hash: string = '^%12hdvjed1~~#29afdmsd`6zvuy@hbkdbc3fn7y7euf|r7934093*7a-|- q`'; var i: integer; begin := 1 length (str) 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; := 1 length (result) result[i] := ansichar (ord (result[i]) xor not (ord (hash[i mod length (hash) + 1]))); end;
i don't know c# either, non-idiomatic.
static string encodedecode(string str) { byte[] hash = new byte[63] { 94, 37, 49, 50, 104, 68, 86, 106, 69, 68, 49, 126, 126, 35, 50, 57, 97, 102, 100, 109, 83, 68, 96, 54, 90, 118, 85, 89, 64, 104, 98, 107, 68, 66, 67, 51, 102, 110, 55, 89, 55, 101, 117, 70, 124, 82, 55, 57, 51, 52, 48, 57, 51, 42, 55, 97, 45, 124, 45, 32, 32, 81, 96 }; encoding ansi = encoding.getencoding(1252); byte[] input = ansi.getbytes(str); byte[] output = new byte[input.length]; (int = 0; < input.length; i++) output[i] = (byte)(input[i] ^ ~hash[(i + 1) % hash.length]); return ansi.getstring(output); }
i have assumed ansi strings encoded windows 1252, happen have encoded legacy data different code page obvious enough how change it.
since c# doesn't have equivalent of delphi's 8 bit string types, sorely tempted use byte[]
rather string
.
done way looks this:
static byte[] encodedecode(byte[] input) { byte[] hash = new byte[63] { 94, 37, 49, 50, 104, 68, 86, 106, 69, 68, 49, 126, 126, 35, 50, 57, 97, 102, 100, 109, 83, 68, 96, 54, 90, 118, 85, 89, 64, 104, 98, 107, 68, 66, 67, 51, 102, 110, 55, 89, 55, 101, 117, 70, 124, 82, 55, 57, 51, 52, 48, 57, 51, 42, 55, 97, 45, 124, 45, 32, 32, 81, 96 }; byte[] output = new byte[input.length]; (int = 0; < input.length; i++) output[i] = (byte)(input[i] ^ ~hash[(i + 1) % hash.length]); return output; }
@groo makes excellent point hash can initialised more cleanly list this:
byte[] hash = ansi.getbytes(@"^%12hdvjed1~~#29afdmsd`6zvuy@hbkdbc3fn7y7euf|r7934093*7a-|- q`");
Comments
Post a Comment