Level 2: Fixed XOR

Task

Write a function that takes two equal-length buffers and produces their XOR combination.

If your function works properly, then when you feed it the string:

1c0111001f010100061a024b53535009181c

... after hex decoding, and when XOR'd against:

686974207468652062756c6c277320657965

... should produce:

746865206b696420646f6e277420706c6179

Explanation

What is Fixed XOR?

XOR is a binary operation. Essentially, two bits are compared. If they are the same, the result is 0; otherwise, the result is 1.

Example

  • 0 + 0 = 0

  • 1 + 0 = 1

  • 0 + 1 = 1

  • 1 + 1 = 0

"Fixed" means that both strings have the same length.

You can learn more about XOR by reading my article on linkedin


Resolution

First, we are going to create a file named task2.py

Understanding the code

  • binascii library is imported to manipulate hexadecimal data.

  • After that, fixed_xor function is defined, which takes two parameters

    • hex1, which contains the first hex string.

    • hex2, which contains the second hex string.

      • bytes1 and bytes2 store the byte representation of hex1 and hex2, respectively.

      • The variable xored_bytes stores the XOR result by following these steps

        • zip(bytes1, bytes2) is a Python function that pairs elements from both byte sequences.

          • Example: a = [1, 2, 3] b = ['x', 'y', 'z']. zip returns [(1, 'x'), (2, 'y'), (3, 'z')

        • a ^ b for a, b in zip(bytes1, bytes2) is a Python expression that iterates through both byte sequences and applies XOR(^) to each pair of bytes.

        • bytes() is a Python function that takes an iterable and returns a bytes object.

  • Next, hex1 and hex2 are initialized with their respective strings.

  • The variable resultado stores the result of fixer_xor(hex1, hex2).

  • Finally, resultado is printed


Result

Last updated