Lesson 3 of 15

XOR Cipher

XOR Cipher

The XOR cipher uses the exclusive-or operation to combine plaintext bytes with a key byte. It is a building block for many modern ciphers.

The XOR Operation

XOR (⊕) has a remarkable property: it is its own inverse.

abb=aa \oplus b \oplus b = a

This means encryption and decryption are identical operations: XOR the data with the key.

Byte-level Encryption

Given a list of plaintext bytes [p0,p1,][p_0, p_1, \ldots] and a single-byte key kk:

ci=pikc_i = p_i \oplus k

Decryption:

pi=cikp_i = c_i \oplus k

Example

Encrypting "Hi" (ASCII 72, 105) with key 42:

BytePlaintextKeyCiphertext
072 (H)4298
1105 (i)4267

Security

Single-byte XOR is trivially broken by frequency analysis — just try all 256 key values. Multi-byte XOR (Vigenère over bytes) is similarly weak. However, XOR with a truly random key as long as the message is the One-Time Pad — provably unbreakable (Shannon, 1949).

Your Task

Implement:

  • xor_encrypt(data, key) — XOR each byte in data (list of ints) with key, return new list
  • xor_decrypt(data, key) — identical operation (XOR is its own inverse)
Python runtime loading...
Loading...
Click "Run" to execute your code.