Skip to content
KALANBLON
Show contents

Chapter 2 of 6 · 15 min

XOR and the one-time pad

By the end of this chapter, you'll be able to

  • Represent a message as bytes and bits
  • Compute an XOR and use its cancelling property to encrypt and decrypt
  • Explain the three conditions of the one-time pad
  • Show why reusing a one-time pad key betrays the messages

A message is made of numbers

For a computer, a text is a sequence of bytes: numbers from 0 to 255. Each byte is written with 8 bits (0s and 1s). In Python, "text".encode() turns a text into bytes (bytes), and .decode() does the reverse.

message = "Yes"
data = message.encode()
for b in data:
    print(b, format(b, "08b"))        # the number, then its 8 bits
89 01011001
101 01100101
115 01110011

The XOR operation

XOR ("exclusive or", written ^ in Python) compares two bits: it gives 1 if they are different, 0 if they are the same. It is applied bit by bit on two bytes.

aba XOR b
000
011
101
110

Its magic property: applying the same key twice cancels the effect. (m ^ k) ^ k always gives back m. So the same operation is used to encrypt and to decrypt.

The same XOR with the same key gives back the message.

Step 5 of 5
Text description of the animation
  1. The letter O is 79, that is 01001111 in binary.
  2. A key byte drawn at random: 54.
  3. We compare the bits two by two: 1 if different, 0 if the same.
  4. The result no longer looks like the letter O.
  5. The same XOR with the same key gives back the message.
def xor_bytes(data, key):
    """XOR byte by byte; the key must be as long as the data."""
    return bytes(d ^ k for d, k in zip(data, key))

message = "Yes".encode()
key = bytes([54, 201, 17])               # a key of the same length

encrypted = xor_bytes(message, key)
print("encrypted:", list(encrypted))
print("decrypted:", xor_bytes(encrypted, key).decode())
encrypted: [111, 172, 98]
decrypted: Yes

The one-time pad

The one-time pad means encrypting with XOR using a key that meets three conditions:

  1. it is as long as the message;
  2. it is truly random;
  3. it is used only once, then destroyed.

Under these conditions, the cipher is perfect: the ciphertext gives no information about the message. For a 3-byte ciphertext, every 3-letter message ("Yes", "Nah", "Meh"…) matches a possible key, all equally likely. Even infinite computing power cannot choose.

In Python, the secrets module provides truly unpredictable bytes: secrets.token_bytes(32) gives 32 random bytes, suitable for cryptography. The random module is made for games and simulations: its values are predictable for anyone who observes enough of them.

import secrets

def xor_bytes(data, key):
    return bytes(d ^ k for d, k in zip(data, key))

message = "Transfer of 25,000 F CFA to Kofi".encode()
key = secrets.token_bytes(len(message))   # random, as long as the message

encrypted = xor_bytes(message, key)
print("message length:", len(message), "bytes")
print("key length    :", len(key), "bytes")
print("back to text  :", xor_bytes(encrypted, key).decode())
message length: 32 bytes
key length    : 32 bytes
back to text  : Transfer of 25,000 F CFA to Kofi

The key changes with every run, but we always get the message back. The big weakness of the one-time pad is practical: to send 1 GB, you must have shared 1 GB of secret key in advance, in person, and never reuse it. That is why it is very rarely used, and why modern ciphers produce a long sequence of bytes from a small key.

Mini-lab: every key is possiblePython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: encrypting a grades file

Write a program that:

  1. encrypts the text "Maths 15, Physics 12, English 17" with a one-time pad generated by secrets;
  2. displays the ciphertext in hexadecimal (with .hex());
  3. checks, with a condition, that decryption gives back exactly the original text, and displays decryption correct.
Hint 1
secrets.token_bytes(n) generates n random bytes. Use n = len(message) where message is already in bytes.
Hint 2
encrypted.hex() displays the bytes in hexadecimal (two characters per byte). For the check: if xor_bytes(encrypted, key) == message:.
Show the solution and common mistakes
import secrets

def xor_bytes(data, key):
    return bytes(d ^ k for d, k in zip(data, key))

message = "Maths 15, Physics 12, English 17".encode()
key = secrets.token_bytes(len(message))
encrypted = xor_bytes(message, key)

print("encrypted:", len(encrypted.hex()), "hexadecimal characters")
if xor_bytes(encrypted, key) == message:
    print("decryption correct")
encrypted: 64 hexadecimal characters
decryption correct

The ciphertext itself changes with every run (the key is random), so we display its length: 32 bytes, that is 64 hexadecimal characters. The comparison is done on the bytes, before decoding.

Common mistakes:

  • Using random.randint for the key: the random module is not made for security, its values can be predicted.
  • Taking a key shorter than the message: zip stops at the shorter one, and the end of the message silently disappears.
  • Forgetting .encode(): you cannot XOR a text (str) with bytes.

Summary

  1. 1A text is a sequence of bytes, and each byte is made of 8 bits.
  2. 2XOR gives 1 when two bits differ; applied twice with the same key, it cancels out.
  3. 3The one-time pad is perfect if the key is as long as the message, random and used only once.
  4. 4Reusing a key makes it vanish in the XOR of two ciphertexts and betrays the messages.
  5. 5For cryptography, use the secrets module, never random.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.