2

I have C snippet(decompiled from IDA) to be translated to Python:

  # v29 = 0;
  # v30 = -1342924972;
  # while ( v29 < v62 ) // v62 is length of string to be decoded
  # {
  #   v31 = (int *)v60;
  #   v32 = __ROL4__(v30, 3);
  #   v33 = *((_BYTE *)v31 + v29) - v29 - v32;
  #   v34 = (int *)v60;
  #   *((_BYTE *)v34 + v29) = v33;
  #   v35 = __ROR4__(v33, 11);
  #   v36 = __ROL4__(v30, 5);
  #   v30 = v30 + (v29++ ^ v36 ^ v35) - 1204489519;
  # }


def decode_msg(dstr, str_len):
  bstr = list(dstr)
  v29 = 0
  v32 = 0
  v33=0
  v35=0
  v30 = -1342924972
  while(v29 < str_len):
    v32 = ((v30 & 0xffffffff) << 3) & 0xffffffff
    v33 = ((hex(ord(bstr[v29])) & 0xff) - v32) & 0xff
    bstr[v29] = v33 & 0xff
    v35 = ((v33 & 0xffffffff) >> 11) & 0xffffffff
    v36 = ((v30 & 0xffffffff) << 5) & 0xffffffff
    v29 = v29 + 1
    v30 = (v30 & 0xffffffff) + (v29 ^ v36 ^ v35) - 1204489519
  return ''.join(bstr)

C code is in comments. The C code decodes a byte array, v60 is the array. I have error:

v33 = ((hex(ord(bstr[v29])) & 0xff) - v32) & 0xff
TypeError: unsupported operand type(s) for &: 'str' and 'int' 

I am totally Python noob. I think hex() converts each item in dstr to a number. So why is it still str?

2
  • 2
    No, hex() converts a number to a string containing the hexadecimal representation of that number. Commented Nov 30, 2016 at 15:51
  • 1
    from IDA to Python: nice touch! you just don't have to use hex, ord is already a number. Commented Nov 30, 2016 at 15:54

2 Answers 2

2

As mentioned, hex returns a string, which obviously does not support bitwise operations like & with a numeric type:

>>> type(hex(3))
<class 'str'>
>>> hex(3) & 0xf
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'str' and 'int'

The ord function already returns an int, so you can just remove the hex function altogether:

>>> ord('c') & 0xff
99
Sign up to request clarification or add additional context in comments.

Comments

2

ord is already an int, you don't need the hex, which returns a string.

And I may be wrong, but this line may give you problems

bstr[v29] = v33 & 0xff

You'd need to cast it to string again:

bstr[v29] = chr(v33 & 0xff)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.