Search code examples
pythonxor

How to calculate the XOR of two bytes in Python?


I used this function to apply the XOR operation between two bytes

 def byte_xor(ba1, ba2):
        """ XOR two byte strings """
        return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)])

I used the function of two bytes R and L

new_R = byte_xor(str(R).encode(), str(self.hash1(str(L).encode())).encode())
  1. where str(R).encode() is equal to b'X: 0x92405a2937fba74a036c002e51dc8405850afe40123b23f2\nY: 0x2b8471aac0e9b2038dd369d376481585bbf0286927d7607e\n(On curve <P192>)'
  2. str(self.hash1(str(L).encode())).encode() is equal to b'4775954696306753387525785228259522227266813277010037244898'
  3. and new_R is equal to b'l\r\x17\x05A\x0c\x06\x02\t\x03R\x02\x0f\x04\x02UQY\x00\x01S\x05\x04\x0eV\x02\x02\nW\x00\x08QQ\n\x06\x02\x02\n\x03\x06YWV\x06\x07\x06\x02\x02R\x02\x00Q\x00>m\x02\x19\x08'

What I don't understand is that when I wanted to get the value of R it didn't give me the entire value, somehow it seems that it gave me half of the actual value:

R = byte_xor(new_R, str(self.hash1(str(L).encode())).encode())
print('This is R:',R)
This is R: b'X: 0x92405a2937fba74a036c002e51dc8405850afe40123b23f2\nY: 0'

Am I doing something wrong? please help me


Solution

  • You probably want to cycle bytes of the second parameter to cover all of the first parameter's content. zip() will only match the common length:

    from itertools import cycle
    
    def byte_xor(ba1, ba2):
            """ XOR two byte strings """
            return bytes([_a ^ _b for _a, _b in zip(ba1, cycle(ba2))])
    
    R = b'X: 0x92405a2937fba74a036c002e51dc8405850afe40123b23f2\nY: 0x2b8471aac0e9b2038dd369d376481585bbf0286927d7607e\n(On curve <P192>)'
    H = b'4775954696306753387525785228259522227266813277010037244898'
    
    N = byte_xor(R,H)
    print(N)
    b'l\r\x17\x05A\x0c\x06\x02\t\x03R\x02\x0f\x04\x02UQY\x00\x01S\x05\x04\x0eV\x02\x02\nW\x00\x08QQ\n\x06\x02\x02\n\x03\x06YWV\x06\x07\x06\x02\x02R\x02\x00Q\x00>m\x02\x19\x08L\x05U\r\r\x02\x05WXU\x03U\x0fU\x07\x03\x00\x00SQ\x01\x03\x0e\\\x06\x05\x04\x0c\n\x04\x0c\r\x07PPT\x07\x00\x0e\x00\x01\x03\x04V\x00\x01\x00\x06U:\x1bx\\\x14WMKNQ\x17\x0be\x08\x0c\x06\x08\x10'