我正在尝试使用 XOR 运算创建加密的十六进制字符串。我想对 my_message 进行编码。我想将
my_message
中的每个字符与 my_key
进行异或。我将它们都转换为字节,然后将它们传递到我的 xor_encrypt
方法中以执行操作并返回 encrypt_byte
,它将作为十六进制编码字符串打印出来。我在 XOR 操作中遇到错误:TypeError: ^: 'int' 和 'bytes' 不支持的操作数类型。我不知道如何纠正这个问题,因为根据我目前的理解 bytes([b ^ byte_key])
应该将它们都转换为正确的字节?我对密码学有点陌生,我正在尽力理解。感谢任何帮助,请随时提出问题,我会在这里回答它们一段时间。预先感谢您!
# 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()}")
你不能
xor
字符串,无论是否二进制。因此,您将字符串中的每个字符转换为其 ASCII 值,然后 ^
。然后将结果转换为字符,最后进行编码。
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
不,您将操作的结果转换为字节。操作本身失败,因为您没有转换操作数。相反:
bytes(b) ^ bytes(byte_key)
你还莫名其妙地制作了一个结果列表,然后想将该单元素列表转换为
bytes
。我删除了它。
您无法对
bytes
字符串进行异或操作,但 bytes
可以作为整数进行迭代。您可以对它们进行异或,将它们构建成 bytearray
并从那里转换为最终形式。
# 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")))