The Wayback Machine - https://web.archive.org/web/20241104200408/https://www.geeksforgeeks.org/xor-cipher/
Open In App

XOR Cipher

Last Updated : 11 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

 



Similar Reads

Difference between Monoalphabetic Cipher and Polyalphabetic Cipher
A Monoalphabetic Cipher is a cipher where each letter in the plaintext is always mapped to the same letter in the ciphertext While a Polyalphabetic Cipher is a cipher where each letter in the plaintext can be encrypted to multiple possible letters in the ciphertext, depending on its position and a more complex algorithm. In this article, we will se
3 min read
Encrypt using XOR Cipher with Repeating Key
Computer Architectures have predefined ASCII values & Binary forms for all printable characters, which allows us to operate bit-wise logic like XOR and most encryption/decryption algorithms depend on. The Key is XOR-operated on the plain text to produce the encrypted text. Only Parameters required to encrypt a plain text using this technique: P
2 min read
Count of subarrays in range [L, R] having XOR + 1 equal to XOR (XOR) 1 for M queries
Given an array, arr[] of N positive integers and M queries which consist of two integers [Li, Ri] where 1 ? Li ? Ri ? N. For each query, find the number of subarrays in range [Li, Ri] for which (X+1)=(X?1) where X denotes the xor of a subarray. Input: arr[]= {1, 2, 9, 8, 7}, queries[] = {{1, 5}, {3, 4}}Output: 6 1Explanation: Query 1: L=1, R=5: sub
12 min read
Latin alphabet cipher
The Latin Alphabet Cipher Encryption Technique is one of the earliest and simplest techniques of encrypting data. It’s simply a type of substitution cipher technique, i.e., each letter of a given text is substituted by its corresponding number as represented in its alphabetical order. For Example, we have given a string as "hello everyone", then it
5 min read
Bifid Cipher in Cryptography
This cipher technique considered more secure compared to other substitution algorithms reason being it breaks the message apart into two separate streams and then recombines them. It is a combination of the Polybius square with the transposition and uses fractionation to achieve diffusion. This encrypting technique invented by Felin Delastelle. It
4 min read
Feistel Cipher
Feistel Cipher model is a structure or a design used to develop many block ciphers such as DES. Feistel cipher may have invertible, non-invertible and self invertible components in its design. Same encryption as well as decryption algorithm is used. A separate key is used for each round. However same round keys are used for encryption as well as de
3 min read
Program to perform a letter frequency attack on a monoalphabetic substitution cipher
Given a string S of size N representing a monoalphabetic cipher, the task is to print the top five possible plain texts that can be decrypted from the given monoalphabetic cipher using a letter frequency attack. Examples: Input: S = "ETAOINSHRDLCUMWFGYPBVKJXQZ"Output: A SIMPLE MESSAGE B TJNQMF NFTTBHF A SIMPLE MESSAGE C UKORNG OGUUCIG C UKORNG OGUU
13 min read
Implementation of Vernam Cipher or One Time Pad Algorithm
One Time Pad algorithm is the improvement of the Vernam Cipher, proposed by An Army Signal Corp officer, Joseph Mauborgne. It is the only available algorithm that is unbreakable(completely secure). It is a method of encrypting alphabetic plain text. It is one of the Substitution techniques which converts plain text into ciphertext. In this mechanis
13 min read
Vernam Cipher in Cryptography
Vernam Cipher is a method of encrypting alphabetic text. It is one of the Substitution techniques for converting plain text into cipher text. In this mechanism, we assign a number to each character of the Plain-Text, like (a = 0, b = 1, c = 2, ... z = 25). Method to take key: In the Vernam cipher algorithm, we take a key to encrypt the plain text w
6 min read
Rail Fence Cipher - Encryption and Decryption
Given a plain-text message and a numeric key, cipher/de-cipher the given text using Rail Fence algorithm. The rail fence cipher (also called a zigzag cipher) is a form of transposition cipher. It derives its name from the way in which it is encoded. Examples:  EncryptionInput : "GeeksforGeeks "Key = 3Output : GsGsekfrek eoeDecryptionInput : GsGsekf
15 min read
Implementation of Affine Cipher
The Affine cipher is a type of monoalphabetic substitution cipher, wherein each letter in an alphabet is mapped to its numeric equivalent, encrypted using a simple mathematical function, and converted back to a letter. The formula used means that each letter encrypts to one other letter, and back again, meaning the cipher is essentially a standard
10 min read
ROT13 cipher
ROT13 cipher(read as - "rotate by 13 places") is a special case of the Ceaser cipher in which the shift is always 13. So every letter is shifted 13 places to encrypt or to decrypt the message. You must think that it is just another caesar cipher so what's different this time? Well the difference is in its implementation. The approach is to use two
10 min read
Implementing Atbash Cipher
Definition: Atbash cipher is a substitution cipher with just one specific key where all the letters are reversed that is A to Z and Z to A. It was originally used to encode the Hebrew alphabets but it can be modified to encode any alphabet. Relationship to Affine: Atbash cipher can be thought of as a special case of Affine cipher with both the keys
7 min read
Keyword Cipher
Keyword cipher is a form of monoalphabetic substitution. A keyword is used as the key, and it determines the letter matchings of the cipher alphabet to the plain alphabet. Repeats of letters in the word are removed, then the cipher alphabet is generated with the keyword matching to A, B, C, etc. until the keyword is used up, whereupon the rest of t
15+ min read
Null Cipher
A null cipher, also known as concealment cipher, is an ancient form of encryption where the plaintext is mixed with a large amount of non-cipher material. Today it is regarded as a simple form of steganography, which can be used to hide ciphertext. There are various options of using the Null Cipher. Here we are taking the first letter from each wor
6 min read
Columnar Transposition Cipher
Given a plain-text message and a numeric key, cipher/de-cipher the given text using Columnar Transposition Cipher The Columnar Transposition Cipher is a form of transposition cipher just like Rail Fence Cipher. Columnar Transposition involves writing the plaintext out in rows, and then reading the ciphertext off in columns one by one. Examples: Enc
12 min read
What is Round Cipher?
Round ciphers are also known as block ciphers, and they are a classification of encryption algorithms that work systematically, converting the plaintext into ciphertext. These algorithms work on a limited number of bits at a time and subject them to a set of mathematical processes called rounds which are used to bring about the act of encryption. I
10 min read
What is Cipher?
Ciphers are the most vital components of cryptography, as it is through them that the protection of information is made possible in the ever-growing digital environment. In the present generation, given the technological advancement especially in the field of communication, the aspect of security is critical. Cipher is used in securing financial tr
7 min read
Transposition Cipher Techniques in Cryptography
Transposition Ciphers are an essential part of cryptography that uses systematic shuffling of plain text characters or bits to secure data by altering their positions based on some defined way or algorithm. Moreover, unlike substitutive codes where different letters substitute others, in these, you just shift about original letters hence it does no
5 min read
Caesar Cipher in Cryptography
The Caesar Cipher is one of the simplest and oldest methods of encrypting messages, named after Julius Caesar, who reportedly used it to protect his military communications. This technique involves shifting the letters of the alphabet by a fixed number of places. For example, with a shift of three, the letter 'A' becomes 'D', 'B' becomes 'E', and s
12 min read
What is Monoalphabetic Cipher?
Monoalphabetic Cipher is a part of the substitution technique in which a single cipher alphabet is used per message (mapping is done from plain alphabet to cipher alphabet). Monoalphabetic cipher converts plain text into cipher text and re-convert a cipher text to plain text. Monoalphabetic Cipher eliminates the brute-force techniques for cryptanal
4 min read
Vigenère Cipher
Vigenere Cipher is a method of encrypting alphabetic text. It uses a simple form of polyalphabetic substitution. A polyalphabetic cipher is any cipher based on substitution, using multiple substitution alphabets. The encryption of the original text is done using the Vigenère square or Vigenère table. The table consists of the alphabets written out
9 min read
Playfair Cipher with Examples
The Playfair cipher was the first practical digraph substitution cipher. The scheme was invented in 1854 by Charles Wheatstone but was named after Lord Playfair who promoted the use of the cipher. In playfair cipher unlike traditional cipher we encrypt a pair of alphabets(digraphs) instead of a single alphabet.It was used for tactical purposes by B
15+ min read
What is Multiplicative Cipher in Cryptography?
A multiplicative cipher is a type of cipher that comes under a monoalphabetic cipher, in which each letter that is present in the plaintext is replaced by a corresponding letter of the ciphertext, according to a fixed multiplication key. In this article, we will learn about the multiplicative cipher and its working for the encryption and decryption
9 min read
Polybius Square Cipher
A Polybius Square is a table that allows someone to convert letters into numbers. To make the encryption little harder, this table can be randomized and shared with the recipient. In order to fit the 26 letters of the alphabet into the 25 cells created by the table, the letters 'i' and 'j' are usually combined into a single cell. Originally there w
5 min read
Substitution Cipher
Hiding some data is known as encryption. When plain text is encrypted it becomes unreadable and is known as ciphertext. In a Substitution cipher, any character of plain text from the given fixed set of characters is substituted by some other character from the same set depending on a key. For example with a shift of 1, A would be replaced by B, B w
6 min read
Autokey Cipher | Symmetric Ciphers
The Autokey Cipher is a method of encrypting messages to keep them secret. It uses a keyword to start the process, but instead of repeating that keyword, it merges letters from the actual message as part of the key. This makes it harder for anyone trying to decode the message without knowing the key. Each letter in the message is shifted based on t
6 min read
Count of integers K in range [0, N] such that (K XOR K+1) equals (K+2 XOR K+3)
Given an integer N, the task is to print the count of all the non-negative integers K less than or equal to N, such that bitwise XOR of K and K+1 equals bitwise XOR of K+2 and K+3. Examples: Input: N = 3Output: 2Explanation: The numbers satisfying the conditions are: K = 0, the bitwise XOR of 0 and 1 is equal to 1 and the bitwise xor of 2 and 3 is
4 min read
Maximize count of pairs whose bitwise XOR is even by replacing such pairs with their Bitwise XOR
Given an array arr[] of size N, the task is to replace a pair of array elements whose Bitwise XOR is even by their Bitwise XOR. Repeat the above step as long as possible. Finally, print the count of such operations performed on the array Examples: Input: arr[] = { 4, 6, 1, 3 }Output: 3Explanation:Step 1: Remove the pair (4, 6) and replace them by t
11 min read
Bitwise XOR of same indexed array elements after rearranging an array to make XOR of same indexed elements of two arrays equal
Given two arrays A[] and B[] consisting of N positive integers, the task is to the Bitwise XOR of same indexed array elements after rearranging the array B[] such that the Bitwise XOR of the same indexed elements of the arrays A[] becomes equal. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 6, 7}Output: 5Explanation:Below are the possible arrangement
14 min read
Practice Tags :
three90RightbarBannerImg