I am trying to create an encrypted hex string using the XOR operation. I want to encode my_message. I want to XOR each character in my_message
against my_key
. I converted both of them to bytes and then passed them into my xor_encrypt
method to perform the operation and return encrypt_byte
which will be printed out as a hex encoded string. I am getting an error on the XOR operation: TypeError: unsupported operand type(s) for ^: 'int' and 'bytes'. I am not sure how to correct this, because from my current understanding bytes([b ^ byte_key])
should convert them both to bytes correct? I am somewhat new to cryptography and I am trying my best to understand. Any help is appreciated, feel free to ask questions I will be here to answer them for a while. Thank you in advance!
# My encryption code
# Take in out byte_msg and XOR it against the byte_key
def xor_encrypt(byte_msg, byte_key):
encrypt_byte = b''
for b in byte_msg:
encrypt_byte += bytes([b ^ byte_key])
return encrypt_byte
# Ascii encoded
my_msg = 'Execute order 66'
my_key = 'b'
# Convert ASCII message and key to Bytes
byte_msg = bytes(my_msg.encode("utf-8"))
print(byte_msg)
key_array = bytes(my_key.encode("utf-8"))
print(key_array)
# Print out the XOR'd message as a hex encoded string
print(f"XOR'd message: {xor_encrypt(byte_msg, key_array).hex()}")
You can not xor
strings, binary or not. So you convert each character in the string to its ASCII value and then ^
. Then convert the result to a character and finally encode it.
def xor_encrypt(byte_msg, byte_key):
encrypt_byte = b''
for b in byte_msg:
encrypt_byte += chr(ord(b) ^ ord(byte_key)).encode()
return encrypt_byte
# Ascii encoded
my_msg = 'Execute order 66'
my_key = 'b'
print(f"XOR'd message: {xor_encrypt(my_msg, my_key).hex()}") # XOR'd message: 271a0701171607420d10060710425454