简体   繁体   English

如何在Python中对十六进制字符串与空间进行异或

[英]How to XOR hex string with space in python

I have 2 cipher texts represented in hex. 我有2个密文表示的密文。 I want to xor cipher text#1 with cipher text#2. 我想用密文#2对密文#1进行异或运算。 This part works fine by xor_strings function. 这部分通过xor_strings函数可以正常工作。 Then, I want to xor every letter in the returned string from xor_strings with spaces character (which has the ASCII code equal to 20 in hexadecimal). 然后,我想对xor_strings返回的字符串中的每个字母与空格字符(其ASCII码等于十六进制的20)进行异或。 But this part is not working with me and when I run the code I get this error: 但是这部分不适用于我,当我运行代码时,出现此错误:

Traceback (most recent call last):
  File "hexor.py", line 18, in <module>
    xored_with_space=xor_space(xored,binary_space)
  File "hexor.py", line 5, in xor_space
    return "".join(chr(ord(xored) ^ ord(binary_space)) for x in xored)
  File "hexor.py", line 5, in <genexpr>
    return "".join(chr(ord(xored) ^ ord(binary_space)) for x in xored)
TypeError: ord() expected a character, but string of length 4 found

Here is the code I am running: 这是我正在运行的代码:

def xor_strings(xs, ys):
    return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(xs, ys))


def xor_space(xored,binary_space):
    return "".join(chr(ord(xored) ^ ord(binary_space)) for x in xored)

a=raw_input("enter first cipher \n")
b=raw_input("enter second cipher \n")
space="20" #hex ASCII value of space

#convert  to binary
binary_a = a.decode("hex")
binary_b = b.decode("hex")
binary_space=space.decode("hex")

xored = xor_strings(binary_a, binary_b).encode("hex")
xored_with_space=xor_space(xored,binary_space)

print xored
print xored_with_space

Can you help me fix the problem? 您能帮我解决问题吗?

use the function that you wrote that does exactly this ... 使用您编写的功能来完成此任务...

def xor_space(xored,binary_space):
    return xor_strings(xored," "*len(xored))

I also suspect you may not fully understand the word binary and its implications 我还怀疑您可能不完全理解二进制一词及其含义

Im not sure what you think a.decode("hex") does ... but Im pretty sure its not doing what you think(although its also possible I am wrong about this) ... 我不确定您认为a.decode("hex")行为是什么...但是我很确定它没有按照您的想法进行(尽管这也可能是我错了)...

Since you know the ordinal value of the space ( 0x20 , or decimal 32 ), just use that instead of binary_space : 由于您知道空格的序数值( 0x20或十进制32 ),因此只需使用该值代替binary_space

def xor_space(xored):
    return "".join(chr(ord(x) ^ 0x20) for x in xored)

However, the actual error in your original function is caused by ord(xored) ; 但是,原始功能中的实际错误是由ord(xored)引起的; you meant to put x there instead of xored . 您打算将x放在此处而不是xored Since xored turns out to be a length 4 string in this case, ord complains about it not being a single character. 由于在这种情况下xored的长度为4个字符串,因此ord抱怨它不是单个字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM