Reputation: 29
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()}")
Upvotes: 0
Views: 1640
Reputation: 1
may be you should use this two function
bitRead()
https://www.arduino.cc/reference/en/language/functions/bits-and-bytes/bitread/
bitWrite()
https://www.arduino.cc/reference/en/language/functions/bits-and-bytes/bitwrite/
Upvotes: 0
Reputation: 77337
You can't XOR bytes
strings but bytes
can be iterated as integers. You can XOR those, build them into a bytearray
and convert to the final form from there.
# My encryption code
# Take in out byte_msg and XOR it against the byte_key
def xor_encrypt(byte_msg, byte_key):
key = byte_key[0]
return bytearray(val^key for val in byte_msg).hex()
# Ascii encoded
my_msg = 'Execute order 66'
my_key = 'b'
print(xor_encrypt(my_msg.encode("utf-8"), my_key.encode("ascii")))
Upvotes: 0
Reputation: 77837
No, you converted the result of the operation to bytes. The operation itself failed, because you didn't convert the operands. Instead:
bytes(b) ^ bytes(byte_key)
You also inexplicably made a list of the result, and then wanted to convert that one-element list to bytes
. I removed that.
Upvotes: 0
Reputation: 7083
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
Upvotes: 2