0

Could you please help me converting this c++ code into python: I am trying to XOR the data

C++ :

void Encrypt(void data, Dword size)
{
    if(size > 0)
        for(DWORD i = size - 1; i > 0; i--)
            ((LPBYTE)data)[i] ^= ((LPBYTE)data)[i - 1];
}
1
  • 1
    I assume you mean void* data. Commented Jun 28, 2012 at 4:48

2 Answers 2

1
def Encrypt(data, size):
    for i in range(size-1, 0, -1):
        data[i] = data[i] ^ data[i-1]

Though this isn't quite pythonic. You'd probably want to remove the explicit size argument and just use len(data)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Antimony, but for some reason i am getting this error "TypeError: unsupported operand type(s) for ^: 'str' and 'str'" Any thoughts?
That's because your running it on strings, for which xor doesn't make sense. You can convert it to numerical bytes by saying map(ord, s) where s is your string.
0

To do this in python, you probably want to use the bytearray class:

def encrypt(data):
    n = len(data)
    for i in range(n-1, 0, -1):
        data[i] ^= data[i-1]      # for this to work, data has to be mutable

f = open('somefile.bin', 'rb')
buf = bytearray(f.read())
f.close()

encrypt(buf)

Note the comment, that you cannot pass a string object, because strings in python are immutable. bytearray on the other hand, is not.

2 Comments

Thanks Jonathon, this seems to work but how come the output data size is doubled?
It works perfectly now. Appreciate your time and sharing your knowledge. You are both brilliant!

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.