Reputation: 3907
I have 2 cipher texts represented in hex. I want to xor cipher text#1 with cipher text#2. This part works fine by xor_strings
function. 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). 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?
Upvotes: 1
Views: 1042
Reputation: 1369
Since you know the ordinal value of the space (0x20
, or decimal 32
), just use that instead of 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)
; you meant to put x
there instead of xored
. Since xored
turns out to be a length 4 string in this case, ord
complains about it not being a single character.
Upvotes: 1
Reputation: 113940
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) ...
Upvotes: 1