1

Im new to python and I have (maybe) a dumb question.

I have to XOR two value. currently my values look like this:

v1 =

<class 'str'>
2dbdd2157b5a10ba61838a462fc7754f7cb712d6

v2 =

<class 'str'>
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8

but the thing is, i need to XOR the actual HEX value instead of the ascii value of the given character in the string.

so for example:

the first byte in the first string is s1 = 2d, in the second string s2 = 5b

def sxor(s1,s2):
    return ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(s1,s2))

this will not work, because it gives back the ASCII value of each character (then XOR them), which is obviously differs from the actual hex value.

1
  • Convert the hex to integers, xor the integers. Commented Oct 9, 2017 at 12:24

3 Answers 3

3

Your mistake is converting the characters to their ASCII codepoints, not to integer values.

You can convert them using int() and format() instead:

return ''.join(format(int(a, 16) ^ int(b, 16), 'x') for a,b in zip(s1,s2))

int(string, 16) interprets the input string as a hexadecimal value. format(integer, 'x') outputs a hexadecimal string for the given integer.

You can do this without zip() by just taking the whole strings as one big integer number:

return '{1:0{0}x}'.format(len(s1), int(s1, 16) ^ int(s2, 16))

To make sure leading 0 characters are not lost, the above uses str.format() to format the resulting integer to the right length of zero-padded hexadecimal.

Sign up to request clarification or add additional context in comments.

Comments

0

Parse the strings into int's then xor the ints:

def sxor(s1,s2):
    i1 = int(s1, 16)
    i2 = int(s2, 16)
    # do you want the result as an int or as another string?
    return hex(i1 ^ i2) 

2 Comments

This produces a 0x at the start and can actually produce a shorter hex value as leading 0 characters are lost.
Good point, I like your much better use of the format() function
0

Works with python3:

_HAS_NUMPY = False
try:
    import numpy
    _HAS_NUMPY = True
except:
    pass

def my_xor(s1, s2):
    if _HAS_NUMPY:
        b1 = numpy.fromstring(s1, dtype="uint8")
        b2 = numpy.fromstring(s2, dtype="uint8")
        return (b1 ^ b2).tostring()

    result = bytearray(s1)
    for i, b in enumerate(s2):
        result[i] ^= b
    return result

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.