Tag Archives: encryption

Implementing XOR Encryption

At times, you need a simple encryption and decryption functionality to secure sensitive information. In my case, I needed to store passwords on disk to implement the “Remember Password” functionality of the GuiClient example of QXmpp.

Instead of going for a 3rd party library where you just need a very basic crypto functionality I will suggest using XOR encryption. XOR encryption is pretty easy to implement. I will also present my implementation of this algorithm using Qt C++.

XOR (Exclusive OR) Encryption or XOR Cipher is a simple symmetric encryption algorithm. It operates according the principle that XORing a data twice with the same key results in the same data.

The first XOR of the data and key gives the encrypted data. Then the decryption involves XORing the encrypted data with the same key.

EncryptedData  = Data ^ Key
Data =  EncryptedData ^ Key

Data: data to be encrypted
Key: secret key or password
EncryptedData: data after encryption
^ represents Exclusive-OR (XOR) operation

Example:

Let us use two binary numbers for Data and Key. The 

Data  = 01101
Key   = 10101

Encrypt:

EncryptedData = Data ^ Key
EncryptedData = 01101 ^ 10101
EncryptedData = 11000

Decrypt:

Data = EncryptedData ^ Key
Data = 11000 ^ 10101
Data = 01101

Implementation of XOR Encryption in Qt C++:

QByteArray calculateXor(const QByteArray& data, const QByteArray& key)
{
 if(key.isEmpty())
   return data;

 QByteArray result;
 for(int i = 0 , j = 0; i < data.length(); ++i , ++j)
 {
   if(j == key.length())
     j = 0;// repeat the key if key.length() < data.length()
   result.append(data.at(i) ^ key.at(j));
 }
 return result;
}