User Tools

Site Tools


Xor Encryption


XOR (eXclusive OR) is a logical operation just like AND/OR/NOT but a little harder to grasp intuitively. In C-style programming languages it's represented with the caret ( ^ )

It can help to think of it as a logical diff. 2 bits are compared and the result is 1 if they're different or 0 if they're the same.

Input Output
0 0 0
0 1 1
1 0 1
1 1 0

One time pads

This makes it useful for encryption when a random sequence is used against a series of bytes. You can encrypt a message by doing

cyphertext=xor(plaintext, key)

and then decrypt with

plaintext=xor(cyphertext, key)

Assuming the key is truly random, the message will be unrecoverable without having a copy of the keyfile. Unfortunately this key needs to be the same length as the message and can never be reused or it leads to other types of decryption attacks.

Repeated password

Often in malware or CTFs you'll see a less secure method which is to use a repeated passphrase. When a file with a section of null chars (0x00) is used the key shows up easily as a visible repeating pattern in the file.

Key Reuse

Another thing you might see is keys being reused. This is a big nono because xoring two messages which use the same key cancels out the encryption on both so the result is the same as an xor of the two repeated messages. Then you can figure it out using basic cryptanalysis looking for expected plaintext and most common letters in English and stuff like that.

Here's some basic python code so you can try it out and see for yourself

code samples

#!/usr/bin/env python 
import binascii
def xor(s1,s2):
    return ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(s1,s2))
def repeat(s, l):
    return (s*(int(l/len(s))+1))[:l]
plaintext='flag{i assume you are doing a ctf right now}'

Further Reading

guides/xor.txt ยท Last modified: 2018/02/21 15:44 by gorzilla