Search code examples
pythonbitwise-operatorsxor

Bitwise xor python


I am trying to solve a problem where I have to decrypt a file. But I found an obstacle. As you can see in the below code, I need to do a bitwise xor between key and number 47.

from Crypto.Cipher import AES
import base64

l1 = open("./2015_03_13_mohamed.said.benmousa.puerta_trasera.enc", "rb");
iv = l1.read(16)
enc = l1.read()
l1.close()

#key = xor beetwen kiv(47) and IV

key = iv
for i in range(len(key)):
    key[i] = key[i] ^ 47

obj = AES.new(key,AES.MODE_CBC, iv)
obj1 = obj.decrypt(enc)

l = open("./ej3.html", "wb").write(obj1)

When I try that I get the following error:

TypeError: unsupported operand type(s) for ^: 'str' and 'int'

I searched things here but I can't get it. Thank you.


Solution

  • because you need an int

    ascii_code_for_a = ord('a') == 97 #convert a character to an ascii integer
    
    int2chr = chr(97) == 'a'  #convert an ascii code back to a character
    

    so just do

    key = list(iv) # first convert it to a list ... strings are unmutable
    for i in range(len(key)):
        key[i] = chr(ord(key[i]) ^ 47)