XOR Encryption Algorithm

The XOR Encryption algorithm is a very effective yet easy to implement method of symmetric encryption. Due to its effectiveness and simplicity, the XOR Encryption is an extremely common component used in more complex encryption algorithms used nowadays.

The XOR encryption algorithm is an example of symmetric encryption where the same key is used to both encrypt and decrypt a message.

Symmetric Encryption: The same cryptographic key is used both to encrypt and decrypt messages.

Symmetric Encryption: The same cryptographic key is used both to encrypt and decrypt messages.

The XOR Encryption algorithm is based on applying an XOR mask using the plaintext and a key:

Reapplying the same XOR mask (using the same key) to the cipher text outputs the original plain text. The following truth table (based on the XOR truth table) demonstrates how the encryption process works.

P (Plain text) K (Key) C (Cipher)
=
P XOR K
K (Key) P (Plain Text)
=
C XOR K
0 0 0 0 0
1 0 1 0 1
0 1 1 1 0
1 1 0 1 1

The XOR encryption algorithm can be applied to any digital/binary information, included text based information encoded using the 8-bit ASCII code. In this case the encryption key can be expressed as a string of characters.

By itself, the XOR encryption can be very robust if:

  • It is based on a long key that will not repeat itself. (e.g. a key that contains as many bits/characters as the plaintext)
  • A new key is randomly generated for any new communication.
  • The key is kept secret by both the sender and the receiver.

When a large quantity of text is to be encrypted, a shorter repeating encryption key is used to match the length of the plain text. However re-using the same key over and over, or using a shorter repeating key results in a less secure method where the cipher text could be decrypted using a frequency analysis.
xor-encryption-keys

Python Code


In this Python code we are using the XOR bitwise operator (in Python: ^) to apply the XOR mask using the plain text and the key.

To improve readability, we are displaying the cipher text in different format: Ascii, Denary, Hexadecimal and Binary format.

Did you like this challenge?

Click on a star to rate it!

Average rating 4.3 / 5. Vote count: 40

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: ,