XOR (Exclusive-Or) is a boolean logic operation that we use widely in cryptography. The following table shows the XOR results according to different inputs:
Input A | Input B | A XOR B Output |
1 | 1 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
0 | 0 | 0 |
It is essential to lay down the fundamentals of cryptography before diving into how XOR encryption and decryption works. Cryptography secures communication between two end-points. For example, if A wants to send a message to B, both A and B require a key to encrypt and decrypt. The steps involved are as follows:
The plaintext is the original text message that A wants to send to B.
The ciphertext is the text encrypted by A using the key.
B will decrypt the ciphertext back to the plaintext using the key and read the message.
The illustration below depicts the steps mentioned above:
The code below shows an example of XOR encryption and decryption using C++.
For the code below, we use the key, U
to encrypt and decrypt. The plaintext,
“Hello! How are you?” is passed through the XorOp
function. The XOR operation takes the first bit of the plaintext and the key and returns the corresponding ciphertext. We call the XorOp
function again to convert the ciphertext back to plaintext. XOR has the property of self-inverse, which makes it suitable for cryptography. The code is as follows:
#include <iostream>#include<bits/stdc++.h>using namespace std;//Function for Encryption and Decryptionvoid XorOp (char text[], int length){//Keychar key = 'U';//XOR Operationfor (int i=0; i<length; i++){text[i] = text[i]^key;cout << text[i];}}int main() {//Plaintextchar plaintext[] = "Hello! How are you?";int length = strlen(plaintext);//Encryptioncout << "Ciphertext: ";XorOp(plaintext, length);cout << endl;//Decryptioncout << "Plaintext: ";XorOp(plaintext, length);cout << endl;return 0;}
Free Resources