0

So I have a bit of Python source code that I want to recreate in C#. The code is about reading and decrypting a binary file. I have tested the function on an existing file and it runs without errors; while the resulting string is not garbled or anything, it does not appear to be useful to me. But that is outside the scope of this question, I only want to know if I have translated the function correctly to C# so it does the same as in Python.

The Python code:

    filename = os.path.basename(path_and_filename)
    key = 0
    for char in filename:
        key = key + ord(char)
    f = open(path_and_filename, 'rb')
    results = ''
    tick = 1
    while True:
        byte = f.read(2)
        if byte:
            if tick:
                key = key + 2
            else:
                key = key - 2
            tick = not tick
            res = struct.unpack('h', byte)[0] ^ key
            results = results + chr(res)
            continue
        break
    f.close()
    return results

path_and_filename is an absolute path to the encrypted file. Here is the C# code I wrote:

        string path = @"C:\Program Files (x86)\Steam\steamapps\common\SolForge\data\released\c28556fb686c8d07066419601a2bdd83\Game_Keywords.dat";
        char[] chars = "c28556fb686c8d07066419601a2bdd83".ToCharArray();
        int key = 0;
        foreach (char c in chars)
        {
            key += c;
        }
        StringBuilder builder = new StringBuilder();


        using (FileStream file = new FileStream(path, FileMode.Open))
        {
            bool tick = true;

            while (true)
            {
                int i = file.ReadByte();
                if (i == -1)
                    break;
                if (tick)
                    key += 2;
                else
                    key -= 2;
                tick = !tick;


                //The next 2 lines are for parsing the short, equivalent(?) to struct.unpack('h', byte)
                i <<= 8;
                i += file.ReadByte();

                i ^= key;
                byte b = (byte)i;
                char c = (char)b;
                builder.Append(c);
            }
        }
        string result = builder.ToString();

Never mind the dirtiness of the code. Will those 2 snippets give the same output to a certain input?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Hackworth
  • 1,069
  • 2
  • 9
  • 23
  • 1
    This should probably be on [Code Review](http://codereview.stackexchange.com) – Evan L Mar 25 '14 at 22:05
  • 1
    Why don't you just test it? – jonrsharpe Mar 25 '14 at 22:14
  • @jonrsharpe because I have no clue about Python, to be honest. I've tried various online interpreters, but I have no way of verifying their output. Also I'm rather stumped by error messages that I didn't expect, and I can't test them against the actual files I'm using. – Hackworth Mar 25 '14 at 23:10

0 Answers0