简体   繁体   中英

Python: XOR hex values in strings

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.

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.

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) 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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