Skip to content

Python XOR string

  • by

If you want to Python XOR two strings, it means you want to XOR each character of one string with the character of the other string. You should then XOR ord() value of each char or str1 with ord() value of each char of str2.

We have utilized the iterator method with the zip() method, ord() method, join() method, and “^” operator for this purpose.

Source: https://stackoverflow.com/

Python XOR string

A simple example codes XOR two strings in Python.

def xor_two_str(a,b):
    xored = []
    for i in range(max(len(a), len(b))):
        xored_value = ord(a[i%len(a)]) ^ ord(b[i%len(b)])
        xored.append(hex(xored_value)[2:])
    return ''.join(xored)
    
print xor_two_str("12ef","abcd")

Or in one line:

def xor_two_str(a,b):
    return ''.join([hex(ord(a[i%len(a)]) ^ ord(b[i%(len(b))]))[2:] for i in range(max(len(a), len(b)))])

print xor_two_str("12ef","abcd")

The following function returns the result hex() which returns a string.

def change_to_be_hex(s):
    return hex(int(s,base=16))

It would help if you used the ^ operator on integers.

def change_to_be_hex(s):
    return int(s,base=16)
    
def xor_two_str(str1,str2):
    a = change_to_be_hex(str1)
    b = change_to_be_hex(str2)
    return hex(a ^ b)
print xor_two_str("12ef","abcd")

Output:

Python XOR string

. Here’s a simple example of how you can XOR two strings in Python:

def xor_strings(s1, s2):
    # Convert strings to bytes
    b1 = bytes.fromhex(s1)
    b2 = bytes.fromhex(s2)
    
    # Perform XOR operation
    result = bytes(x ^ y for x, y in zip(b1, b2))
    
    # Convert result back to hexadecimal string
    return result.hex()

# Example usage
string1 = "dead"
string2 = "beef"
result = xor_strings(string1, string2)
print("XOR result:", result)

In this code:

  • The xor_strings function takes two hexadecimal strings s1 and s2 as input.
  • It converts the strings into bytes using bytes.fromhex() method.
  • It performs XOR operation using a generator expression within zip().
  • Finally, it returns the result as a hexadecimal string using .hex() method.

Comment if you have any doubts or suggestions on this Python xor topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading