Boot.dev Blog ยป Cryptography ยป Why Is Exclusive or (XOR) Important in Cryptography?

Why is Exclusive Or (XOR) Important in Cryptography?

By Lane Wagner on January 18, 2020

Curated backend podcasts, videos and articles. All free.

Want to improve your backend development skills? Subscribe to get a copy of The Boot.dev Beat in your inbox each month. It's a newsletter packed with the best content for new backend devs.

If you are getting into cryptography, or just trying to understand the fundamentals, you may have noticed that the exclusive or (XOR) operation is used quite often, especially in ciphers. XOR is a simple bitwise operation that allows cryptographers to create strong encryption systems, and consequently is a fundamental building block of practically all modern ciphers. Let’s dive into the details and see what makes XOR so important.

What is XOR? ๐Ÿ”—

XOR, or “exclusive or” operates on binary data. It returns true if both of its inputs are opposites (one false and one true), otherwise, it returns false. You may see the operator written this way: โŠ•.

XOR example

For example, in Go, the code would be something like:

func exclusiveOr(a bool, b bool) bool {
	return a != b
}

XOR Cipher - The Perfect Cipher ๐Ÿ”—

It is interesting to note that if:

  1. The key is the same size as the message
  2. The key is kept secret and generated truly randomly

Then the XOR cipher is certainly impossible to crack. This is known as a one-time pad. However, a simple XOR shouldn’t be used in production due to the key length needing to be too long to be practical.

Cipher Example ๐Ÿ”—

For instance, let’s simply encrypt the word “hi”

  1. First, convert “hi” to binary, here is a free tool)

01101000 01101001

  1. Next, create a random secret key that has the same length:

01010010 01000101

  1. Then, create an encrypted message by XOR’ing the message and the key:
01101000 01101001 ("hi")
XOR
01010010 01000101 (secret key)
=
00111010 00101100 (encrypted message)
  1. Finally, decrypt the message by XOR’ing the key with the encrypted message again:
00111010 00101100 (encrypted message)
XOR
01010010 01000101 (secret key)
=
01101000 01101001 ("hi")

Why does it work? ๐Ÿ”—

XOR works as a cipher because it is its own inverse.

๐‘Ž = (๐‘Ž โŠ• ๐‘) โŠ• ๐‘

And, as we demonstrated in our example:

encrypted = message โŠ• key
and
message = encrypted โŠ• key

Is XOR used in production ciphers? ๐Ÿ”—

The simple XOR cipher isn’t used in production because it is impractical to use keys that are the same length as the message body. However, the XOR is still extremely useful. In fact, it is used in almost all symmetric encryption algorithms. XOR is the primary operation in the “add round key” step of AES-256. It is also used in the DES cipher.

Find a problem with this article?

Report an issue on GitHub