Open In App

XOR Cipher

Improve
Improve
Like Article
Like
Save
Share
Report

XOR Encryption is an encryption method used to encrypt data and is hard to crack by brute-force method, i.e generating random encryption keys to match with the correct one. 

Below is a simple implementation in C++. The concept of implementation is to first define XOR – encryption key and then to perform XOR operation of the characters in the String with this key which you want to encrypt. To decrypt the encrypted characters we have to perform XOR operation again with the defined key. Here we are encrypting the entire String. 

C++




// C++ program to implement XOR - Encryption
#include<bits/stdc++.h>
  
// The same function is used to encrypt and
// decrypt
void encryptDecrypt(char inpString[])
{
    // Define XOR key
    // Any character value will work
    char xorKey = 'P';
  
    // calculate length of input string
    int len = strlen(inpString);
  
    // perform XOR operation of key
    // with every character in string
    for (int i = 0; i < len; i++)
    {
        inpString[i] = inpString[i] ^ xorKey;
        printf("%c",inpString[i]);
    }
}
  
// Driver program to test above function
int main()
{
    char sampleString[] = "GeeksforGeeks";
  
    // Encrypt the string
    printf("Encrypted String: ");
    encryptDecrypt(sampleString);
    printf("\n");
  
    // Decrypt the string
    printf("Decrypted String: ");
    encryptDecrypt(sampleString);
  
    return 0;
}


Java




// Java program to implement XOR - Encryption
class XOREncryption
{
    // The same function is used to encrypt and
    // decrypt
    static String encryptDecrypt(String inputString)
    {
        // Define XOR key
        // Any character value will work
        char xorKey = 'P';
  
        // Define String to store encrypted/decrypted String
        String outputString = "";
  
        // calculate length of input string
        int len = inputString.length();
  
        // perform XOR operation of key
        // with every character in string
        for (int i = 0; i < len; i++) 
        {
            outputString = outputString + 
            Character.toString((char) (inputString.charAt(i) ^ xorKey));
        }
  
        System.out.println(outputString);
        return outputString;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String sampleString = "GeeksforGeeks";
  
        // Encrypt the string
        System.out.println("Encrypted String");
        String encryptedString = encryptDecrypt(sampleString);
  
        // Decrypt the string
        System.out.println("Decrypted String");
        encryptDecrypt(encryptedString);
    }
}
  
// This code is contributed by Vivekkumar Singh


Python3




# Python3 program to implement XOR - Encryption
  
# The same function is used to encrypt and
# decrypt
def encryptDecrypt(inpString):
  
    # Define XOR key
    # Any character value will work
    xorKey = 'P';
  
    # calculate length of input string
    length = len(inpString);
  
    # perform XOR operation of key
    # with every character in string
    for i in range(length):
      
        inpString = (inpString[:i] + 
             chr(ord(inpString[i]) ^ ord(xorKey)) +
                     inpString[i + 1:]);
        print(inpString[i], end = "");
      
    return inpString;
  
# Driver Code
if __name__ == '__main__':
    sampleString = "GeeksforGeeks";
  
    # Encrypt the string
    print("Encrypted String: ", end = "");
    sampleString = encryptDecrypt(sampleString);
    print("\n");
  
    # Decrypt the string
    print("Decrypted String: ", end = "");
    encryptDecrypt(sampleString);
  
# This code is contributed by Princi Singh


C#




// C# program to implement XOR - Encryption
using System;
      
public class XOREncryption
{
    // The same function is used to encrypt and
    // decrypt
    static String encryptDecrypt(String inputString)
    {
        // Define XOR key
        // Any character value will work
        char xorKey = 'P';
  
        // Define String to store encrypted/decrypted String
        String outputString = "";
  
        // calculate length of input string
        int len = inputString.Length;
  
        // perform XOR operation of key
        // with every character in string
        for (int i = 0; i < len; i++) 
        {
            outputString = outputString + 
            char.ToString((char) (inputString[i] ^ xorKey));
        }
  
        Console.WriteLine(outputString);
        return outputString;
    }
  
    // Driver code
    public static void Main(String[] args)
    {
        String sampleString = "GeeksforGeeks";
  
        // Encrypt the string
        Console.WriteLine("Encrypted String");
        String encryptedString = encryptDecrypt(sampleString);
  
        // Decrypt the string
        Console.WriteLine("Decrypted String");
        encryptDecrypt(encryptedString);
    }
}
  
// This code has been contributed by 29AjayKumar


Javascript




// JavaScript program to implement XOR - Encryption
  
// The same function is used to encrypt and
// decrypt
function encryptDecrypt(inpString)
{
    inpString = inpString.split("");
  
    // Define XOR key
    // Any character value will work
    let xorKey = 'P';
  
    // calculate length of input string
    let len = inpString.length;
  
    // perform XOR operation of key
    // with every character in string
    for (let i = 0; i < len; i++)
    {
        inpString[i] = (String.fromCharCode((inpString[i].charCodeAt(0)) ^ xorKey.charCodeAt(0)));
        process.stdout.write(inpString[i]);
    }
    return inpString.join("");
}
  
// Driver program to test above function
let sampleString = "GeeksforGeeks";
  
// Encrypt the string
process.stdout.write("Encrypted String: ");
sampleString = encryptDecrypt(sampleString);
process.stdout.write("\n");
  
// Decrypt the string
process.stdout.write("Decrypted String: ");
encryptDecrypt(sampleString);
  
// This code is contributed by phasing17


Output

Encrypted String: 55;#6?"55;#
Decrypted String: GeeksforGeeks

Time Complexity : O(N) , here N is length of given string.

Space Complexity : O(1),since no extra space used. 

The basic idea behind XOR – encryption is, if you don’t know the XOR-encryption key before decrypting the encrypted data, it is impossible to decrypt the data. For example, if you XOR two unknown variables you cannot tell what the output of those variables is. Consider the operation A XOR B, and this returns true. Now if the value of one of the variable is known we can tell the value of another variable. If A is True then B should be False or if A is False then B should be true according to the properties of the boolean XOR operation. Without knowing one of the value we can not decrypt the data and this idea is used in XOR – encryption.

Related Articles: 
Vigenère Cipher 
Caesar Cipher

 



Last Updated : 11 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads