Lane Wagner

Posted on • Originally published at qvault.io on

# Why is Exclusive Or (XOR) Important in Cryptography?

If you are getting into cryptography, or just trying to understand the fundamentals, you may have noticed that the exclusive-or operation is used quite often, especially in ciphers.

## 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.

An example in go code would be something like:

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

## XOR Cipher β The Perfect Cipher

The XOR operation can be used as a simple cipher for encrypting and decrypting messages with a single key. This is known as symmetric encryption.

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 cipher is 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

As a simple example, letβs encrypt the word βhiβ

1. Convert βhiβ to binary, here is a free tool: https://www.rapidtables.com/convert/number/ascii-to-binary.html)
``````01101000 01101001
``````
1. Create a random secret key that has the same length:
``````01010010 01000101
``````
1. 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. 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.

Lane on Dev.to: wagslane

The post Why is Exclusive Or (XOR) Important in Cryptography? appeared first on Qvault.

David Paine

Thanks for sharing. The information is really helpful.
For the text to binary translation, here is another link, check it out
dnschecker.org/text-to-binary-tran...

Shashi

Good piece. Thank you!

finrodfelagund

Thanks for the lesson.

## 12 Rarely Used Javascript APIs You Need

Practical examples of some unique Javascript APIs that beautifully demonstrate a practical use-case.