Reputation: 901
On trying to xor bytes in python3:
import os,binascii
import numpy as np
def xor_byte_hex_strings(a, b) :
return bytes(x ^ y for x, y in zip(a, b))
number_of_bytes = 2
random_bytes = []
random_bytes_str = binascii.b2a_hex(os.urandom(number_of_bytes))
random_bytes.append(random_bytes_str)
print(random_bytes_str)
print(bytearray(random_bytes_str))
random_bytes_str = binascii.b2a_hex(os.urandom(number_of_bytes))
random_bytes.append(random_bytes_str)
resultant = xor_byte_hex_strings(random_bytes[0], random_bytes[1])
print("resultant = ", bytearray(resultant))
print(random_bytes)
resultant = xor_byte_hex_strings(random_bytes[1], resultant)
print(resultant)
The result is b'\x03\x03\x0cU' instead of b'13ce. How do we convert the format from b'\x03\x03\x0cU' to b'13ce?
Upvotes: 1
Views: 3757
Reputation: 7887
Why not work with strings and int
s to make your life easier?
import os,binascii
def xor_strings(a, b):
result = int(a, 16) ^ int(b, 16) # convert to integers and xor them together
return '{:x}'.format(result) # convert back to hexadecimal
number_of_bytes = 2
random_bytes = []
# decode() to turn it into a str.
random_bytes_str = binascii.b2a_hex(os.urandom(number_of_bytes)).decode()
random_bytes.append(random_bytes_str)
random_bytes_str = binascii.b2a_hex(os.urandom(number_of_bytes)).decode()
random_bytes.append(random_bytes_str)
print(random_bytes)
xored = xor_strings(*random_bytes)
print("resultant = ", xored.encode())
print([random_bytes[1], xored])
resultant = xor_strings(random_bytes[1], xored)
print(resultant.encode()) # encode() will turn it back to bytes if you want bytes
Output:
['4588', '3af9']
resultant = b'7f71'
['3af9', '7f71']
b'4588'
Upvotes: 1