◆ Rebuild

Part 15 · Knowledge and Science

Codes, Ciphers and Encryption

How to keep a message or a record readable only by the people meant to read it, and how to prove who wrote it. Transposition and substitution ciphers and how they are broken, cipher discs and wheels, the unbreakable one-time pad, rotor cipher machines, and — in plain words — the computer ciphers, fingerprints, public keys and digital signatures that guard modern networks; plus the everyday habits that actually keep records private.

Difficulty
●●●●●
Time
An evening to learn and use the hand ciphers; a day to make a cipher wheel; weeks to build a rotor machine; months to program computer encryption and check it properly
Steps from zero
78 prerequisites →

You need first

Logic and BinaryThe Internet

This unlocks

—
The full path from nothing — 78 steps before this one
  1. Fire
  2. Cordage and Rope
  3. Stone Tools
  4. Finding and Preparing Clay
  5. Finding and Identifying Ores
  6. Sulfur
  7. Writing and Numbers
  8. Hunting and Trapping
  9. Basic Woodworking
  10. The Kiln
  11. Pottery
  12. Charcoal
  13. Arithmetic and Fractions
  14. Hides and Leather
  15. Lime
  16. Bricks
  17. Salt
  18. Mercury
  19. Lye and Potash
  20. Fermentation
  21. The Wheel and Axle
  22. Logic and Binary
  23. Glass
  24. Firebrick and Refractories
  25. Bellows
  26. Saltpeter
  27. The Lathe
  28. Gears
  29. Glass Fibre and Glass Wool
  30. Copper Smelting
  31. Iron (the Bloomery)
  32. Lead
  33. Laboratory Glassware
  34. Sulfuric Acid
  35. Pumps
  36. The Waterwheel
  37. Lenses
  38. Blacksmithing
  39. Gold and Silver
  40. The Blast Furnace and Cast Iron
  41. Bronze
  42. Hydrochloric Acid
  43. The Battery
  44. The Vacuum Pump
  45. Magnets
  46. The Spectroscope
  47. Steel
  48. Chimneys, Stoves and Heating
  49. Bearings and Lubrication
  50. The Steam Engine
  51. The Light Bulb
  52. Copper Wire
  53. Electrolysis
  54. Photography
  55. Hydrogen, Oxygen and Gases
  56. Centrifugal Pumps and Fans
  57. Machine Tools
  58. The Generator
  59. The Electromagnet
  60. The Vacuum Tube
  61. The Electric Arc Furnace
  62. Ammonia
  63. The Telegraph
  64. Ice and Refrigeration
  65. The Telephone
  66. Pure Silicon
  67. Ventilation and Air Conditioning
  68. Semiconductors and the Transistor
  69. Clean Rooms
  70. Integrated Circuits
  71. Lasers
  72. The Computer
  73. Fibre Optics
  74. Making Microchips
  75. Networks and the Internet
  76. Programming
  77. Microprocessors and Personal Computers
  78. The Internet
  79. Codes, Ciphers and Encryption

Do them roughly in this order. See it on the tech tree →

Why it matters

Some things must be written down but not read by everyone: a patient's illness, a family's savings, a ballot, a contract under negotiation, the combination of the seed vault, the password to the waterworks computer. A letter can be opened on the way (The Post); a radio message is heard by anyone with a receiver (Radio); a message on a network passes through machines run by strangers (The Internet). Encryption scrambles a message so that only someone holding the right key can unscramble it.

The same mathematics does a second job that matters as much: proving who wrote a message and that nobody changed it. Once orders, payments and votes travel by wire, a forged order is as dangerous as a read one.

How it works

A few words used throughout:

  • Plaintext: the message as written. Ciphertext: the scrambled message.
  • Cipher: a method of scrambling letter by letter or bit by bit. Code: a book that replaces whole words or phrases with code groups ("BRAVO 41" = "send more seed potatoes").
  • Key: the secret setting that controls the cipher — a word, a number, a wheel order. Encrypt with the key; decrypt with it.
  • Cryptanalysis: breaking ciphers without the key.

The most important rule, set down by Auguste Kerckhoffs in 1883: assume the enemy knows your method; all the secrecy must be in the key. Methods leak — machines are captured, clerks talk, manuals are copied. A key can be changed tomorrow; a method cannot.

Every cipher in this chapter uses one or both of two ideas: transposition (shuffle the order of the letters) and substitution (replace each letter with another).

What you need

For You need
Hand ciphers Paper, pencil, and a stove to burn worksheets
Cipher disc Stiff card, thin wood or brass sheet, a pair of dividers, a rivet
Cipher wheel 20–30 hardwood or metal discs turned on a The Lathe, a threaded rod, letter punches or fine paint
One-time pad A bag of 26 lettered tokens (or 10 numbered ones), small paper sheets, carbon paper, a strongbox (Locks and Keys)
Rotor machine Hardwood or plastic discs, brass pins and springs, fine wire (Copper Wire), key switches, lamps, a battery
Computer encryption A The Computer or microcontroller you can program

Transposition: shuffling the letters

The scytale

The Spartans' scytale is a wooden rod of agreed thickness, 3–4 cm across and 30 cm long. Wind a strip of leather or paper 1 cm wide round it in a tight spiral, write along the rod, and unwind: the strip shows a jumble, which reads again only on a rod of the same diameter. Anyone who guesses the trick simply tries rods, so it is a teaching toy, but it shows the idea.

Columnar transposition

Agree a keyword, say WATER. Write it across the top of the page, number its letters in alphabetical order (A=1, E=2, R=3, T=4, W=5), and write the message in rows under it. Fill the last row with dummy letters (X).

W A T E R
5 1 4 2 3
---------
S E N D M
O R E S A
L T T O T
H E M I L
L X X X X

Read the columns in number order: ERTEX DSOIX MATLX NETMX SOLHL. To decrypt, the receiver counts the letters (25), knows there are 5 columns of 5, writes each group down its numbered column, and reads across: SEND MORE SALT TO THE MILL.

Done once it is fairly easy to break; done twice, with two keywords, it served armies into the 20th century.

Substitution: replacing the letters

The Caesar shift and why it fails

Replace each letter with the one 3 places further on: MEET AT DAWN becomes PHHW DW GDZQ. There are only 25 possible shifts; try them all and one reads as language.

A mixed alphabet — each letter replaced by any other, in a scrambled order agreed as the key — has an astronomical number of possible keys (about 4 × 10²⁶), yet it is still easy to break, by frequency analysis. In ordinary English text, E is about 12–13% of all letters, T 9%, A 8%, O, I, N, S, H, R 6–7.5%, while J, Q, X and Z are well under 1%. Count the ciphertext letters: the commonest probably stands for E. Then look for a common three-letter group (THE), doubled letters and short words. A few hundred letters usually fall in an hour. (Count a long book in your own language to get its table.)

The lesson: any cipher that always turns the same plaintext letter into the same ciphertext letter is weak, however clever it looks.

Polyalphabetic ciphers

The cure is to change the substitution from letter to letter. In the Vigenère cipher, number the letters A=0 to Z=25, write a keyword repeatedly under the message, and add each key letter to the message letter above it, wrapping round after Z. With key LEMON, the first five letters of ATTACK become L-X-F-O-P. The same letter now comes out differently in different places, and plain frequency counts fail. But the key repeats, and from the 1850s analysts learned to find its length from repeated groups and break each column by frequency.

The cipher disc

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Q M Z B X F T K A E W J R P G L V C O Y D N U H I S inner disc turns Key: inner Q set under A Cipher disc outer ring fixed: plain A–Z, 12 cm inner disc turns: scrambled letters, 9 cm K E M M U B C E R D L S E B Q G B T C N N C A H C R N T B S D H T U U S B H S S M B E H B R E M J N E R I D S J R L V F D S L S U G L N D R W C O S B T G W P V 7 3 12 1 15 9 4 16 2 11 6 14 8 13 5 10 Blue: any other row, sent copied down as the ciphertext Yellow: the message row disc numbers below: the day's key order Cipher wheel 20–30 discs, 5 cm across, on a threaded rod nut at each end: loose to turn, tight to lock
Fig. 1 Two hand cipher devices. Left, a cipher disc: the outer ring is fixed, the inner disc turns on a rivet; set a key letter against A and read across. Right, a cipher wheel: discs each carrying a different scrambled alphabet are threaded on a spindle in a secret order and turned until the message reads along one row; any other row is sent.

A cipher disc is two concentric discs on a centre pin: the outer one carries the plain alphabet, the inner, turning one a scrambled cipher alphabet.

Making one. Cut an outer disc 12 cm across and an inner disc 9 cm across from stiff card, thin plywood (Plywood, Veneer and Boards) or 0.5 mm brass (Sheet Metal and Rolling). Each must be divided into 26 equal parts of 13.85°. There is no neat construction for 26, so do it by trial with dividers: set them to about 1.45 cm on the rim of the 12 cm disc (about 1.09 cm on the 9 cm disc) and step round; if the 26th step overshoots or falls short, adjust by a twenty-sixth of the error and step again, until the last step lands exactly on the first mark. Rule lines from the centre through the marks. Letter the outer ring A–Z; letter the inner ring in a scrambled order (draw 26 letter tokens from a bag). Punch the centre and join the discs with a rivet or a pin and washer so the inner one turns stiffly but does not slip.

Using it. The key says which inner letter starts against outer A, and how often to change: for instance, move the inner disc on by an agreed number of places after every word. Then the disc is a polyalphabetic cipher in your pocket. In a good disc every letter sits squarely in its cell, and two copies set alike give identical letters.

The cipher wheel

A cipher wheel (Thomas Jefferson's "wheel cypher") is a row of discs on a spindle, each with a different scrambled alphabet round its rim. The key is the order of the discs on the spindle.

Making one. Turn 20–30 discs of close-grained hardwood or brass on a The Lathe, about 5 cm across and 6 mm thick, with a 6 mm centre hole. Divide each rim into 26 as above (or with a dividing plate, Machine Tools) and stamp, burn or paint a fresh scrambled alphabet on each, drawn from a bag of letter tokens. Number each disc. Thread them on a threaded rod with a nut at each end, loose to turn, tight to lock. Make two identical sets, one for each end of the line.

Using it. Put the discs on in the key order. Turn them until the first 25 letters of the message read along one row; tighten the nut; copy down any other row as the ciphertext. The receiver sets the ciphertext along one row of an identically ordered wheel and turns the cylinder slowly: only one row reads as language. Change the disc order every day.

The one-time pad

The one-time pad is the only cipher that can be proved unbreakable, as Claude Shannon showed in 1949. It is a Vigenère cipher whose key is truly random, as long as the message, and used only once.

The arithmetic. Number the letters A=0 to Z=25. Add each key letter to the message letter and wrap round past 25 (subtract 26):

message   H  E  L  L  O         7   4  11  11  14
key       X  M  C  K  L        23  12   2  10  11
sum                            30  16  13  21  25
minus 26 if over 25             4  16  13  21  25
cipher    E  Q  N  V  Z

To decrypt, subtract the key letters (adding 26 if the result is negative). Because every key letter is equally likely, the ciphertext EQNVZ could be any five-letter word at all: with a different key it decrypts to LATER or PANIC just as well. There is nothing to analyse.

Making pads.

  1. Make a bag of 26 identical tokens — wooden squares, clay discs, bone counters — each marked with one letter, all feeling the same in the hand.
  2. Shake, draw one without looking, write the letter, put it back, shake again. Never "make up" random letters: people favour some letters and patterns.
  3. Write the letters in groups of five on small numbered sheets, with carbon paper so both copies are written at once. A practised pair makes 500–700 letters an hour.
  4. Seal each set of sheets and keep it in a locked box (Locks and Keys).
  5. Write the sheet number openly at the start of each message. Use each sheet once, then burn it and stir the ash.

For teleprinters and computers, the same thing is done in binary: combine each message bit with a random key bit by exclusive-or (XOR, Logic and Binary) — 1 if the two bits differ, 0 if they match. XOR the result with the same key and the message comes back. This was Gilbert Vernam's paper-tape cipher of 1917 (The Teleprinter).

Warning Never use a pad twice. If two messages are encrypted with the same key, subtracting one ciphertext from the other cancels the key completely and leaves the two messages mixed together, which skilled people can then pull apart. In the 1940s this single mistake let American analysts read thousands of supposedly unbreakable Soviet messages. A pad that is not truly random is just as fatal.

The pad's weakness is key delivery: every letter of secret you want to send needs a letter of pad carried there beforehand, by a trusted hand. It suits a few vital links — a government and its embassies, a hospital and its outlying clinics — not a whole nation's mail.

Code books

A code book lists the few hundred words and phrases a service needs ("SEND DOCTOR", place names, numbers), each with a random four- or five-letter group, in two books: one ordered by plaintext for encoding, one by code group for decoding. Codes shorten telegrams, but groups repeat and can be guessed from events, so for secrecy encrypt the code groups too.

The rotor cipher machine

D K P T W Z B steps one place every key press Lamps Exit Rotor 1 Rotor 2 Rotor 3 Entry Key 4.5 V battery only 6 of each rotor's 26 contacts are drawn 26 flat contacts Ratchet, 26 teeth, and one carry notch About 10 cm across Spring pins touch next rotor Flat contacts Secret wiring inside contacts to pins, scrambled Letter ring on the rim
Fig. 2 How a rotor machine scrambles a letter. A key press sends current from the battery through the entry plate and three wired rotors to the exit plate, where it lights one lamp. After each key press the right-hand rotor steps one place, so the next letter takes a completely different path. Below, one rotor taken apart.

A rotor cipher machine does a polyalphabetic cipher with a period so long that the key never repeats within a message, and does it as fast as a clerk can type.

The rotor. A disc about 10 cm across and 2 cm thick, of hardwood, hard rubber or moulded plastic (Early Plastics). One face has 26 flat brass contacts in a circle about 7 cm across; the other face has 26 spring-loaded brass pins in the same circle. Inside, fine insulated wire joins each contact to a pin in a scrambled order — the rotor's wiring, chosen by drawing tokens from a bag. Round the rim, a ring of 26 letters shows its position, a ratchet of 26 teeth lets it be stepped, and one notch decides when it carries the next rotor on.

The machine. Three to five rotors sit side by side on a spindle, each rotor's pins touching the next one's contacts. Pressing a key sends current from a 4.5 V battery into one of 26 wires of a fixed entry plate, through every rotor and a fixed exit plate, to one of 26 lamps marked with letters (or to the print magnets of a The Teleprinter). To decrypt, a changeover switch joins the keyboard to the exit plate and the lamps to the entry plate, so the current runs the same path backwards. A lever under the key first steps the right-hand rotor one place by its ratchet, so the path changes before every letter. When the right rotor passes its notch, it pushes the middle rotor on one step, like the wheels of a mileage counter (Clockwork, Music Boxes and Counting Machines). Three rotors give 26 × 26 × 26 = 17,576 positions before the pattern repeats.

The key is which rotors are used, their order, and their starting positions — changed every day from a printed key list.

Making one. Wire one rotor first and test it with battery and lamp: each contact must reach exactly one pin. Then make the keyboard (switches as in Microprocessors and Personal Computers), the lampboard and the stepping pawls, with a spring detent so each rotor stops exactly where its pins centre on the next rotor's contacts. Build two machines with identical rotor sets, and check that a 200-letter message typed into one decrypts perfectly on the other.

Learning from history. The German Enigma sent the current back through the rotors from a fixed reflector, which saved the changeover switch but meant no letter could ever encrypt to itself. That flaw, and operators who began messages with predictable phrases, let Polish and then British codebreakers read much of its traffic. Avoid the reflector, step the rotors irregularly (the American SIGABA, never broken in service, used a second bank of rotors to decide which ones moved), and never start messages with stock words.

Encryption by computer

Ciphers in software

Inside a computer, ciphers work on bits (Logic and Binary). A modern block cipher takes a block of, say, 128 bits of message and a 128-bit key, and puts the block through 10 or more rounds. Each round substitutes small groups of bits through a fixed look-up table, shuffles and mixes them across the block, and combines them with part of the key by XOR. After a few rounds, changing one bit of the message or the key changes about half of the output bits, unpredictably.

A 128-bit key has about 3 × 10³⁸ possible values: trying a billion billion a second would take ten million million years.

Do not invent your own cipher for anything that matters. Use a published design that many skilled people have attacked for years without success, write it down exactly with test values (a known key, a known message and the ciphertext they must give), and check every new program against them. Keep them in the library with the programs (Libraries and Preserving Knowledge).

Fingerprints and passwords

A hash or fingerprint function turns a file of any length into a short number, typically 256 bits; changing a single comma changes it completely, and nobody can find two files with the same fingerprint. Equal fingerprints prove a copied book or program is identical to the original. A computer should never store passwords, only a fingerprint of each password mixed with a random number (a salt); a thief who steals the file gets no passwords.

Choosing a passphrase. Number a list of 7,776 short, common words with five dice (11111 to 66666). Roll five dice per word and take six words: about 77 bits of randomness, far beyond guessing, yet memorable as a silly sentence.

Public keys, in plain words

Every cipher so far needs the same secret key at both ends, carried there safely. Public-key methods avoid that.

Secrecy: lock with the public key, open with the private key message anyone locks it ciphertext: safe to send only the owner can open it message Public key given to everyone Private key kept secret Signature: seal with the private key, check with the public key message fingerprint 7F3A 91C2 … seal sig signature, sent with the message does it match the fingerprint? anyone can check genuine and unchanged Change one letter of the message and its fingerprint changes completely, so the check fails.
Fig. 3 Public keys and signatures. Top: anyone can lock a message with your public key, but only your private key opens it. Bottom: you seal a fingerprint of the message with your private key; anyone can check the seal with your public key, which proves you wrote it and that it has not been changed.

Think of open padlocks. You make many padlocks that all open with one key, which you keep, and hand the open padlocks out freely. Anyone can snap one shut on a box — but only you can open it. The padlock is your public key; your key is your private key.

The mathematics uses calculations that are easy one way and practically impossible to undo. In the RSA method, multiplying two large primes is easy; finding them again from the product is not. A toy example, with numbers far too small to be safe:

  • Choose two primes, 61 and 53. Their product n = 3233 is public.
  • From them, choose a public number e = 17 and a private number d = 2753 (they are linked through (61 − 1) × (53 − 1) = 3120: 17 × 2753 leaves 1 when divided by 3120).
  • To send the number 65, anyone computes 65¹⁷ and keeps only the remainder after dividing by 3233: 2790.
  • Only the holder of d can undo it: 2790²⁷⁵³, remainder after dividing by 3233, is 65 again.

Real keys use numbers about 600 digits long, which no known computer can factor. In practice, the slow public-key step is used only to agree a fresh random key, and a fast block cipher carries the message.

Digital signatures

Run the padlock backwards. To sign, encrypt the message's fingerprint with your private key. Anyone can decrypt it with your public key and compare it with the message's own fingerprint. A match proves the signature was made with your private key and that not one letter has changed since.

The weak point is knowing that a public key really belongs to its claimed owner. Exchange keys in person, or read their fingerprints aloud by telephone. On a large network a trusted office checks identities and signs people's public keys; a signed key is a certificate.

Keeping records private

Most secrets are lost through careless people, not broken ciphers.

  1. Decide what is secret: medical and personal records, accounts, keys, ballots. Too much secrecy hides mistakes.
  2. Lock it up: locked cabinets, a register of who opened them, numbered wax or lead seals so tampering shows (Locks and Keys). Each person sees only the records their work needs.
  3. Guard and back up the keys. An encrypted record whose key is lost is gone for ever. Seal written copies of important keys in two places, or split each key between two trusted people.
  4. Check unusual orders by a second route: telephone, messenger or an agreed challenge word (The Internet).
  5. Destroy properly: burn used pads and worksheets; break old disks.

How to tell it worked

  • Give a clever friend a 100-letter ciphertext and the method, but not the key, for a week. Hand ciphers other than the pad often fall; this teaches respect.
  • Round trip: everything decrypts exactly as sent, on the twin wheel or machine too.
  • Pads: in 1,000 letters of pad each letter should appear about 38 times, nearly all between 26 and 51, with no obvious patterns.
  • Software: every program reproduces the published test values exactly; changing one bit of key changes about half the output.

Note Troubleshooting. Decrypt gives gibberish from the start → wrong key, wrong pad sheet, wrong disc order or rotor start; check the key list date. Decrypt goes wrong part-way → a letter dropped or added in sending. Send in five-letter groups with a group count at the end, and number the groups. Cipher disc copies disagree → the 26 divisions are uneven; redivide. Rotor machine lights two lamps or none → a pin not touching its contact or a broken wire; test each rotor alone with battery and lamp.

Dangers

  • False confidence: a weak cipher believed strong is worse than none, because people write what they never would in the open.
  • Lost keys lose everything they lock. Records that must outlive their keepers need a sealed, recorded way to recover them.
  • Secrecy can shelter wrongdoing. Encryption protects the weak from the strong, but also hides theft and conspiracy. A community should agree in the open who may keep which secrets and when records must be opened to inspection (Organising a Community).
  • People are the weak point: keys left on desks, pads reused, clerks bribed or threatened. Keep registers and never let one person alone hold an important key.

Going further

  • Networks and the Internet and The Internet: encrypt every link and sign every software update.
  • Large future quantum computers could break today's public-key methods; newer methods built on different hard problems have been designed and published to replace them.

How it was first done

Plutarch describes the Spartan scytale; Suetonius says Julius Caesar wrote to his friends with each letter shifted three places. The Arab scholar al-Kindi described frequency analysis in Baghdad in the 9th century. Leon Battista Alberti invented the cipher disc around 1467, the first polyalphabetic cipher; Giovan Battista Bellaso published the keyword method in 1553, which later took the name of Blaise de Vigenère. Charles Babbage broke it privately in the 1850s; Friedrich Kasiski published a method in 1863. Thomas Jefferson described his wheel cypher in the 1790s; Étienne Bazeries reinvented it in 1891, and the US Army adopted it as the M-94 in 1922. Auguste Kerckhoffs stated his principles in 1883.

Gilbert Vernam of AT&T built the paper-tape cipher in 1917, and Joseph Mauborgne saw that a random key used once made it unbreakable; Claude Shannon proved it in 1949. Rotor machines were invented by several people around 1917–1919, among them Edward Hebern in America and Arthur Scherbius in Germany (the Enigma). Marian Rejewski and his Polish colleagues broke the Enigma mathematically in 1932; Alan Turing, Gordon Welchman and the codebreakers of Bletchley Park built on their work during the Second World War.

The US standard computer cipher DES appeared in 1977, and its successor AES, designed by the Belgians Joan Daemen and Vincent Rijmen, in 2001. Whitfield Diffie and Martin Hellman published public-key exchange in 1976, and Ron Rivest, Adi Shamir and Leonard Adleman the RSA method in 1977. It later emerged that James Ellis, Clifford Cocks and Malcolm Williamson at the British intelligence agency GCHQ had found the same ideas a few years earlier and kept them secret.

Source: content/entries/knowledge/encryption.md