XOR Bitwise Operations
XOR is commonly used method for cryptography.
Basic
For XORing, we can use ^
operator.
Here is Python script example to XOR.
Also use the XOR key for xoring a target value.
The above operation does the following calculation internally.
- Convert the decimal
21
of the target to the binary (10101
). - Convert the decimal
2
of the key to the binary (00010
). - XOR the bits at each position as below.
By the way, each value can be replaced individually as follows.
In CTF, we may be able to use this principle to calculate the xor key.
XOR Characters
We can also XOR each character.
The above operation does the following calculation internally.
- Convert the character ‘a’ to the Unicode
97
. It’s1100001
in binary. - Convert the character ‘b’ to the Unicode
98
. It’s1100010
in binary. - XOR the bits at each position as below.
XOR Strings
In addition, we can also XOR strings by XORing the bits at each position.
ciphertext = "5d41402abc4b2a76b9719d911017c592"
key = "secret"
# Convert each string to bytes
ciphertext_bytes = bytes.fromhex(ciphertext)
key_bytes = key.encode()
# XOR operation
xored_bytes = bytes(a ^ b for a, b in zip(ciphertext_bytes, key_bytes))
# Convert the result to Hex
xored_hex = xored_bytes.hex()
print("Result:", xored_hex)
The above operation does the following calculation.
- Convert the ciphertext to the binary.
- Convert the XOR key to the binary.
- Loop each byte and XOR each one.
-
Convert the result bytes to Hex.
-
Using
strxor
of PyCryptodomeWe can also use
strxor
method ofpycryptodome
module in Python.
XOR with Pwntools
We can easily XOR using the xor
module of pwntools
.
First off, install pwntools
if you don't have.
To decrypt the encrypted text with XOR, write Python script such as below.
from pwn import xor
ciphertext = "5d41402abc4b2a76b9719d911017c592"
key = "secret"
xored = xor(bytes.fromhex(ciphertext), key.encode())
Brute Force XOR Key with 0/Null
If we specify 0 or \x00
to the target value, the result is the key as it is.
Using the principle, we may be able to get the XOR key by brute forcing.
xor_key = b'secret'
null_payload = b''
for i in range(10):
null_payload += b'\x00'
result = bytes([a ^ b for a, b in zip(null_payload, xor_key)])
print(result.decode())
The output of the above script will be the following: