XOR: Simple and Effective Encryption
XOR is often used in information security to encrypt data. A good example of
this is in the creation of a one-time pad. A one-time pad is a type of encryption
in which a message in encrypted by combining a randomly generated key. Because
the key is completely random, an attacker who does not have the key can not
decrypt the message, even if they know the algorithm being used.
XORing works by comparing two pieces of data bit, by bit. If the bits are different
the XOR operation will output a 1. It the two bits are the same, the XOR operation
will output a 0.
Let's say we have two pieces of information, A and B. A is 1010 and B is 0101.
When we XOR A and B together, we get the following:
1 XOR 0 = 1
0 XOR 1 = 1
1 XOR 0 = 1
0 XOR 1 = 1
So the result of XORing A and B is 1111.
We can use this process to encrypt data with a secret key. The result will be
very difficult for anyone to read unless they also have the key. The result of
XOR in a series of 1's and 0's, which is not very easy for humans to read. To
make things more readable, we can convert it to a different format, such as
hexadecimal for base64. This will allow us to share the encrypted message with
others without revealing the key.
Here is an example in Python.
First, we'll define a function to encrypt the message using XOR and a key:
def encrypt(message, key):
result = ''
for i in range(len(message)):
test = message[i]
key_to_encrypt = key[i%len(key)]
result += chr(ord(test) ^ ord(key_to_encrypt))
# Return the result as a hexadecimal string
return result.encode('utf-8').hex()
Next, we'll define a function to decrypt the message using XOR and the same key:
def decrypt(message, key):
result = ""
message = bytes.fromhex(message).decode("utf-8")
for i in range(len(message)):
text = message[i]
key_to_decrypt = key[i%len(key)]
result += chr(ord(text) ^ ord(key_to_decrypt))
return result
Finally, we can test the functions by encrypting and decrypting a message:
# Test the encryption and decryption functions
key = 'secret'
message = 'Hello, world!'
encrypted = encrypt(message, key)
print("enc msg:",encrypted)
decrypted = decrypt(encrypted, key)
print("dec msg:",decrypted)
# The output should be the original message
assert decrypted == message
Now, this isn't perfect and should only be used sparingly. When ever possible use
proper encryption!
Download the xor script.
While writing this I used https://gchq.github.io/CyberChef/#recipe=XOR({'option':'UTF8','string':'secret'},'Standard',false)To_Hex('None',0)&input=SGVsbG8sIHdvcmxkIQ and found it rather helpful.