尝试对单个字符键的字节字符串进行 XOR 运算



我正在尝试使用XOR操作创建一个加密的十六进制字符串。我想对my_message进行编码。我想对my_message中的每个角色进行 XOR 对抗my_key.我将它们都转换为字节,然后将它们传递到我的xor_encrypt方法中以执行操作并返回encrypt_byte该将打印为十六进制编码字符串。我在 XOR 操作上收到错误:类型错误:^ 不支持的操作数类型:"int"和"字节"。我不确定如何纠正这一点,因为根据我目前的理解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可以迭代为整数。您可以对这些进行 XOR 操作,将它们构建到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")))

最新更新