XOR cipher

Last updated

In cryptography, the simple XOR cipher is a type of additive cipher , [1] an encryption algorithm that operates according to the principles:

Contents

A 0 = A,
A A = 0,
A B = B A,
(A B) C = A (B C),
(B A) A = B 0 = B

For example where denotes the exclusive disjunction (XOR) operation. [2] This operation is sometimes called modulus 2 addition (or subtraction, which is identical). [3] With this logic, a string of text can be encrypted by applying the bitwise XOR operator to every character using a given key. To decrypt the output, merely reapplying the XOR function with the key will remove the cipher.

Example

The string "Wiki" (01010111 01101001 01101011 01101001 in 8-bit ASCII) can be encrypted with the repeating key 11110011 as follows:

01010111 01101001 01101011 01101001
11110011 11110011 11110011 11110011
=10100100 10011010 10011000 10011010

And conversely, for decryption:

10100100 10011010 10011000 10011010
11110011 11110011 11110011 11110011
=01010111 01101001 01101011 01101001

Use and security

The XOR operator is extremely common as a component in more complex ciphers. By itself, using a constant repeating key, a simple XOR cipher can trivially be broken using frequency analysis. If the content of any message can be guessed or otherwise known then the key can be revealed. Its primary merit is that it is simple to implement, and that the XOR operation is computationally inexpensive. A simple repeating XOR (i.e. using the same key for xor operation on the whole data) cipher is therefore sometimes used for hiding information in cases where no particular security is required. The XOR cipher is often used in computer malware to make reverse engineering more difficult.

If the key is random and is at least as long as the message, the XOR cipher is much more secure than when there is key repetition within a message. [4] When the keystream is generated by a pseudo-random number generator, the result is a stream cipher. With a key that is truly random, the result is a one-time pad, which is unbreakable in theory.

The XOR operator in any of these ciphers is vulnerable to a known-plaintext attack, since plaintextciphertext = key. It is also trivial to flip arbitrary bits in the decrypted plaintext by manipulating the ciphertext. This is called malleability.

Usefulness in cryptography

The primary reason XOR is so useful in cryptography is because it is "perfectly balanced"; for a given plaintext input 0 or 1, the ciphertext result is equally likely to be either 0 or 1 for a truly random key bit. [5]

The table below shows all four possible pairs of plaintext and key bits. It is clear that if nothing is known about the key or plaintext, nothing can be determined from the ciphertext alone. [5]

XOR Cipher Trace Table
PlaintextKeyCiphertext
000
011
101
110

Other logical operations such and AND or OR do not have such a mapping. For example consider the table for AND below:

AND Cipher Trace Table
PlaintextKeyCiphertext
000
010
100
111

If the ciphertext were 0, then there is a 2/3 chance that the plaintext was 0 too. And if the ciphertext was 1, then the plaintext would have to be 1. This clearly reveals information about the text that the XOR approach does not. [a]

Example implementation

Example using the JavaScript programming language. [6]

functionxor_Encrypt(inputString,key){letencrypted_Hex="";for(leti=0;i<inputString.length;i++){constplain_string=inputString.charCodeAt(i);constkey_Char=key.charCodeAt(i%key.length);constxor_Result=plain_string^key_Char;// Perform XOR operation// Convert the XOR result to a two-digit hexadecimal string// Pad with '0' if it's a single digit (e.g., 5 -> "05")lethex=xor_Result.toString(16);if(hex.length<2){hex="0"+hex;}encrypted_Hex+=hex;}returnencrypted_Hex;}functionxorDecrypt(hexInput,key){letdecrypted_String='';// Step 1: Convert hexInput string into an arrayconstbytes=[];// Iterate through the hex string two characters at a timefor(leti=0;i<hexInput.length;i+=2){// Take a two-character hex substring (e.g., "AB")consthexa_Byte=hexInput.slice(i,i+2);// Convert hex substring to an integer (e.g., "AB" -> 171)bytes.push(parseInt(hexa_Byte,16));}// Step 2: XOR each byte with the key and convert back to characterfor(leti=0;i<bytes.length;i++){constbyte_Value=bytes[i];constkey_Char=key.charCodeAt(i%key.length);constxor_Result=byte_Value^key_Char;// Perform XOR operation// Convert the XOR result back to a characterdecrypted_String+=String.fromCharCode(xor_Result);}returndecrypted_String;}

Another example using the Python programming language. [b]

fromosimporturandomdefgenerate_key(length:int)->bytes:"""Generate encryption key."""returnurandom(length)defxor_strings(s,t)->bytes:"""Concatenate xor two strings together."""ifisinstance(s,str):# Text strings contain single charactersreturn"".join(chr(ord(a)^b)fora,binzip(s,t)).encode("utf8")else:# Bytes objects contain integer values in the range 0-255returnbytes([a^bfora,binzip(s,t)])message="This is a secret message"print("Message:",message)key=generate_key(len(message))print("Key:",key)cipherText=xor_strings(message.encode("utf8"),key)print("cipherText:",cipherText)print("decrypted:",xor_strings(cipherText,key).decode("utf8"))# Verifyifxor_strings(cipherText,key).decode("utf8")==message:print("Unit test passed")else:print("Unit test failed")

A shorter example using the R programming language, based on a puzzle posted on Instagram by GCHQ.

secret_key<-c(0xc6,0xb5,0xca,0x01)|>as.raw()secret_message<-"I <3 Wikipedia"|>charToRaw()|>xor(secret_key)|>base64enc::base64encode()secret_message_bytes<-secret_message|>base64enc::base64decode()xor(secret_message_bytes,secret_key)|>rawToChar()

See also

References

Notes

  1. There are 3 ways of getting a (ciphertext) output bit of 0 from an AND operation:
    Plaintext=0, key=0;
    Plaintext=0, key=1;
    Plaintext=1, key=0.
    Therefore, if we know that the ciphertext bit is a 0, there is a 2/3 chance that the plaintext bit was also a 0 for a truly random key. For XOR, there are exactly 2 ways, so the chance is 1/2 (i.e. equally likely, so we cannot learn anything from this information)
  2. This was inspired by Richter 2012

Citations

  1. Tutte 1998 , p. 3
  2. Lewin 2012, pp. 14–19.
  3. Churchhouse 2002 , p. 11
  4. Churchhouse 2002 , p. 68
  5. 1 2 Paar & Pelzl 2009, pp. 32–34.
  6. armasahar/XOR-Cipher, 2025-09-26

Sources