---
title: "Analysis"
description: "Guess which cipher it is. Brute force a Caesar. Read the index of coincidence. Find the Vigenère key length. Find what opens a salted blob, or what the first letters spell."
canonical_url: "https://ciphers.agntn.dev/guide/analysis"
---
# Analysis

> Guess which cipher it is. Brute force a Caesar. Read the index of coincidence. Find the Vigenère key length. Find what opens a salted blob, or what the first letters spell.

## Which cipher is it?

Somebody hands you `FMXVEDKAPHFERBNDKRXRSREFMORUDSDKDVSHVUFEDKAPRKDLYEVLRHHRH`. Vigenère? An agent will say Vigenère, it always does. Ask first:

```bash
ciphers guess "FMXVEDKAPHFERBNDKRXRSREFMORUDSDKDVSHVUFEDKAPRKDLYEVLRHHRH"
```

```text
Family guess (57 characters, 57 A-Z letters, lang=en, IoC 0.0627 (en plaintext ~0.065, uniform random ~0.038)), most likely first:

1. substitution-multiplicative, substitution-shift, substitution-reflection (medium): affine, caesar, atbash
   IoC 0.0627 is close to en plaintext, one alphabet throughout, and affine a=3 b=5 makes the letters fit en.
   Next: ciphers_decode with cipher affine and a=3, b=5.
```

Not a Vigenère at all. It's Example 1.10 from Stinson, and a=3, b=5 is his key. The test suite checks that too.

The layout goes first. Those are rules, not statistics, so they come back sure of themselves:

- Dots and dashes are Morse.
- Digits 1 to 5 in pairs are Polybius, single digits tap code.
- Pairs with a digit 6 to 9 mean a wider Polybius square. Bring the alphabet.
- Numbers up to 26 with something between them are A1Z26.
- Only A, D, F, G, V and X is ADFGVX.
- Two letters in groups of five is Bacon.
- Hex goes by length: whole 16-byte blocks point at AES and its friends, 8-byte ones at DES and its friends, anything else at a stream.
- `U2FsdGVkX1` is the `Salted__` header CryptoJS writes.
- A ZIP local header, `504b0304` in hex or `UEsDB` in base64, points at zipcrypto. The archive announces itself.

Letters get statistics. Do they fit the language as they stand? Then they were moved, not replaced, so rail fence, columnar or a route. IoC near plaintext? One alphabet. The guess then tries all 311 affine keys, Caesar and Atbash included, and names the one that reads. Near 0.038? Several alphabets, and `period` is next. An even count with no J and no doubled pair smells like Playfair. Add a doubled pair and it's four-square, which bifid can pass for. English pairs peeking through in plain sight? That's a two-square getting lazy, and it moves ahead of four-square. Flat letters with a J, no spaces and whole blocks of 2 or 3? Could be Hill. Numbers from 22 to 110, none of them ending in 1? Two square cells added up, so Nihilist.

What if those numbers spell something? Decimal character codes can look like Nihilist sums or wider Polybius squares. That's encoding, not encryption. The guess puts the decoded text ahead of the ciphers:

```bash
ciphers guess "72 69 76 76 79 32 87 79 82 76 68"
```

```text
Family guess (22 characters, 0 A-Z letters, lang=en), most likely first:

Not a cipher by the look of it: decimal character codes that read "HELLO WORLD".
   Every number is a printable ASCII code, and the letters they spell fit en.
   Next: encodings_decode with encoding decimal, from @agntn/encodings.

1. fractionation (low): nihilist
   11 numbers from 22 to 110 and none ending in 1, as two square cells added together give.
   Next: ciphers_decode with cipher nihilist, which needs key.
2. fractionation (low): polybius
   Digit pairs with a 9, so a 9×9 square. Polybius reads it with the alphabet that filled it. These numbers fit nihilist too.
   Next: ciphers_decode with cipher polybius, which needs alphabet.

Candidates, not a verdict: only a decode that reads settles it.
```

The guess needs at least four printable ASCII codes. Spaces, commas, tabs and line breaks can separate them. Runs of three digits need no separators. Decoded tabs and line breaks also count as gaps between words.

Ten letters with counts that fit the language push every cipher candidate to low. Word shapes like `Hello` leave confidence alone. Mostly letters and digits can pass when no number cipher claims them. Think `flag{n0t_a_c1ph3r}`.

What about text hiding in hex or base64? The hex `48656c6c6f20776f726c6421` reads `Hello world!`. Its length suggests a stream cipher. Recognized text puts those candidates at low. Decoded text comes first. Here's a Polish pangram in hex.

```bash
ciphers guess "5a61c5bcc3b3c582c4872067c499c59b6cc485206a61c5bac5842069206e69652074796c6b6f20746f" --lang pl
```

```text
Family guess (82 characters, 23 A-Z letters, lang=pl), most likely first:

Not a cipher by the look of it: hex that reads "Zażółć gęślą jaźń i nie tylko to".
   Every character the hex spells in UTF-8 is a letter or a printable ASCII code, and the letters they spell fit pl.
   Next: encodings_decode with encoding hex, from @agntn/encodings.

1. substitution-permutation, permutation, polyalphabetic, arx (low): aes-ctr, aes-cfb, aes-ofb, rc4, xor, rabbit, salsa20, xsalsa20, chacha20, xchacha20, aes-ccm, chacha20-poly1305, aes-ocb, aes-xts, aes-cbc-mac
   82 hex digits, no whole number of blocks: a stream cipher or a block cipher in a stream mode.
   Next: ciphers_decode with cipher aes-ctr, which needs key and iv.

Candidates, not a verdict: only a decode that reads settles it.
```

A font demo isn't AES. The bytes must be valid UTF-8. Letters from any script count alongside printable ASCII, including combining accents. Accents come off for the letter fit: `ż` counts as Z, `ł` as L. The frequency tables hold base letters only. French accents get the same treatment.

What if there's no table for the script? Russian in hex and kana in base64 can pass on word shapes. That leaves cipher confidence alone. Tables cover en, pl and ja in romaji only. Invalid UTF-8, a byte order mark, emoji and punctuation beyond ASCII, such as curly quotes, stay bytes.

What about numbers pretending to be text? Hex made of digits alone needs ten decoded letters that fit the language. Base64 in a single case, or made of digits alone, faces the same rule. That's picky. It should be. If a Polybius or ADFGVX layout claims the input, neither encoding gets a turn.

Decimal numbers past ASCII are read as Unicode code points when spaces or commas split them. An unbroken digit run stays ASCII only. Past ASCII, the guess needs ten letters that fit the language. At least a third must be plain A to Z. Word shapes aren't enough.

Past 191, every second number or so is a letter in some script. `200 300 400 500` spells `ÈĬƐǴ`, but stays a list of numbers. A price list isn't a letter.

Polish clears that bar:

```bash
ciphers guess "90 97 380 243 322 263 32 103 281 347 108 261 32 106 97 378 324" --lang pl
```

That reads `Zażółć gęślą jaźń`.

The next step says to read each number as a code point. The `decimal` codec in `@agntn/encodings` takes bytes and stops at 255. The cost: Russian decimal code points aren't recognized without a Russian table. The same text in hex is.

The bar matters. HELLO WORLD with the Nihilist key TSAR gives `67 58 42 73 78 95 45 84 75 57`. As character codes, that's `C:*IN_-TK9`. Quite a message for a tsar. The guess reports Nihilist at medium and no character codes.

How sure is it? I encrypted 40 English and 40 Polish samples with fourteen letter ciphers, Caesar to Enigma. From 200 letters the right family came first in at least 37 of 40, for each of them. At 30 letters a Caesar lands on top about half the time. So a short text comes back `low` and keeps the other side on the list. Bifid is the stubborn one. A keyed square can leave the letter counts looking English, and counting single letters can't see past that.

```ts
import { guessFamily } from "@agntn/ciphers";

const guess = guessFamily(ciphertext, "en");
guess.candidates[0].ciphers; // ["affine", "caesar", "atbash"]
guess.candidates[0].options; // { a: 3, b: 5 }
```

<table>
<thead>
  <tr>
    <th>
      Field
    </th>
    
    <th>
      Meaning
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        candidates
      </code>
    </td>
    
    <td>
      Most likely first, empty when nothing points anywhere
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        families
      </code>
    </td>
    
    <td>
      <code>
        info().family
      </code>
      
       of the candidate's ciphers
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ciphers
      </code>
    </td>
    
    <td>
      Built-in ciphers to try, the likeliest first
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        confidence
      </code>
    </td>
    
    <td>
      <code>
        high
      </code>
      
      , <code>
        medium
      </code>
      
       or <code>
        low
      </code>
      
      , never <code>
        high
      </code>
      
       on a handful of letters
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        signal
      </code>
    </td>
    
    <td>
      What in the text points there
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        options
      </code>
    </td>
    
    <td>
      The key, when the guess found one that reads
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        needs
      </code>
    </td>
    
    <td>
      Options the first cipher needs that the guess can't find
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        encoding
      </code>
    </td>
    
    <td>
      Character codes the text spells, with its <code>
        name
      </code>
      
      , the decoded <code>
        text
      </code>
      
       and the <code>
        signal
      </code>
    </td>
  </tr>
</tbody>
</table>

Candidates, not a verdict. The decode that reads is the verdict. `--lang pl` or `ja` changes the language the letters should fit.

## Brute force

A Caesar has 25 keys. The attack is all of them, then read:

```bash
ciphers brute "KHOOR ZRUOG"
```

```text
shift= 3 -> HELLO WORLD
shift= 6 -> EBIIL TLOIA
shift=14 -> WTAAD LDGAS
...
```

There is no dedicated function for this in the library, and there shouldn't be. It's `create("caesar").decode(text, { shift })` in a loop from 1 to 25 - that's what the command, the `ciphers_caesar_brute` tool and the [landing panel](https://ciphers.agntn.dev/) run. Shift 0 isn't on the list. It would be the input, and the library refuses it as a shift anyway.

The command and `ciphers_caesar_brute` sort the same 25, the most English line first. With `--lang pl` on the command, or `lang: "pl"` on the tool, the most Polish one leads. `ja` does the same for Japanese romaji. A model then reads the answer on line one instead of wading to shift 17.

So how do you tell `HELLO WORLD` from `EBIIL TLOIA`? Not by letters. Both are made of common ones, and counted one by one the junk wins. English goes by letter pairs inside words instead, that's `pairFit`. `HE` is one English pair in 63, `II` one in 5800. On 10 characters of Pride and Prejudice or Frankenstein, pairs put the right shift first 92% of the time, single letters 72%. Polish and Japanese have no pair table yet, so they still rank by `fit`. A lone short word can still lose, and that's why all 25 come back.

The tool cuts them, though. Only its top line comes back whole, the rest stop at 80 characters with a `…`. Past that length and with the right `lang`, the ranking put the right shift first in all 6000 English and Polish samples I threw at it, and in 2000 Japanese ones. And 24 full copies of a 2000 character ciphertext are about 23 000 tokens of wrong answers. Eighty characters is plenty to see that a lower line reads. For the whole of it, decode with that shift. The command prints every line whole, a terminal has no context window to save.

## Frequency

```ts
import { analyzeFrequency } from "@agntn/ciphers";

const analysis = analyzeFrequency("DWWDFN DW GDZQ", "en");
analysis?.counts; // [["D", 4], ["W", 3], ["F", 1], ...] sorted by count
analysis?.reference; // "ETAOINSHRDLCUMWFGYPBVKJXQZ"
analysis?.ic; // index of coincidence
analysis?.referenceIc; // what plaintext in the language scores, 0.065 for English
analysis?.fit; // how much the letters look like English, higher is closer
analysis?.pairFit; // the same for letter pairs inside words, English only
```

`analyzeFrequency(text, language)` uppercases, drops everything outside A to Z and counts. No letters at all - `undefined`, not an empty table, so check before you read. The language picks the reference order, `en`, `pl` or `ja`. The English order is the Wikipedia letter frequency table. The Polish one is [PWN's count of the IPI PAN corpus](https://sjp.pwn.pl/poradnia/haslo/frekwencja-liter-w-polskich-tekstach;7072.html), base letters only, because the diacritics are gone before anything gets counted: `ż` counts for nothing, not for `z`.

Japanese is `ja`, romaji in Hepburn: `shi`, `chi`, `tsu`, `fu`, `ji`. I didn't find a published letter table for it, only keystroke counts from typing in the Kunrei style, where `C` and `J` never show up. So the table is built from the hiragana counts of [Chikamatsu et al. (2000)](https://doi.org/10.3758/BF03200819), a year of newspaper text. Each kana is spelled the way Japan's passport Hepburn table does it, `きょ` as `kyo`, and `っ` doubles the next consonant. L, Q, V and X get almost nothing instead of zero, so a loanword costs some fit but doesn't wipe it out. It only knows kana, not kanji readings. That's why it expects less `u`, `s` and `h` than real text has.

<table>
<thead>
  <tr>
    <th>
      Field
    </th>
    
    <th>
      Meaning
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        total
      </code>
    </td>
    
    <td>
      Letters counted
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        counts
      </code>
    </td>
    
    <td>
      <code>
        [letter, count]
      </code>
      
       pairs, most frequent first
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        reference
      </code>
    </td>
    
    <td>
      Expected order for the language
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ic
      </code>
    </td>
    
    <td>
      Index of coincidence, missing with fewer than two letters
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        referenceIc
      </code>
    </td>
    
    <td>
      Index of coincidence of plaintext in the language, from the same table as <code>
        reference
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        fit
      </code>
    </td>
    
    <td>
      Mean log probability of one letter in the language. Closer to zero reads more like it
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        pairFit
      </code>
    </td>
    
    <td>
      Mean log probability of a letter pair inside a word, from <a href="https://norvig.com/ngrams/" rel="nofollow">
        Norvig's counts
      </a>
      
      . English only, missing when no word has two letters
    </td>
  </tr>
</tbody>
</table>

## Reading the index of coincidence

The IC is the chance that two letters picked from the text are the same. English sits near 0.065, Polish near 0.057 because its letters spread more evenly, uniform random near 0.038. Japanese romaji goes the other way. Five vowels carry about half the text, so it sits high: Kokoro and Rashomon measure 0.082, the kana table says 0.088. That one number tells you which family you are looking at before you try a single key:

- Monoalphabetic substitution (Caesar, Atbash, Affine) keeps the histogram shape and only relabels the bars. IC stays high, and the tallest ciphertext letter is probably E.
- Polyalphabetic (Vigenère, Alberti) spreads one plaintext letter over several ciphertext letters. IC drops toward 0.038 and the histogram goes flat. Time to look for a period.
- Transposition (rail fence, columnar, route) moves letters without changing them. The histogram is the plaintext's, only the words are gone.

The [Playground](https://ciphers.agntn.dev/playground) draws the histogram for any text, expected order next to actual.

## The CLI

```bash
ciphers frequency "DWWDFN DW GDZQ"
ciphers frequency "ZAŻÓŁĆ GĘŚLĄ JAŹŃ" --lang pl
ciphers frequency "KIMIGAYO WA CHIYO NI" --lang ja
```

One bar per letter, expected and actual order, then the IC with the two reference values next to it so you don't have to remember them. English text gets one more line, the [quadgram fit](#scoring-your-own-decoding), with its own two references.

## Key length

The IC dropped to 0.038. Now what? A Vigenère key repeats, and that's the whole weakness. Take every fifth letter under a five-letter key and you're holding one Caesar. Get the length right and every column reads like plaintext again.

```bash
ciphers period "CHREEVOAHMAERATBIAXXWTNXBEEOPHBSBQMQEQERBWRVXUOAKXAOSXXWEAHBWGJMMQMNKGRFVGXWTRZXWIAKLXFPSKAUTEMNDCMGTSXMXBTUIADNGMGPSRELXNJELXVRVPRTULHDNQWTWDTYGBPHXTFALJHASVBFXNGLLCHRZBWELEKMSJIKNBHWRJGNMGJSGLXFEYPHAGNRBIEQJTAMRVLCRREMNDGLXRRIMGNSNRWCHRQHAEYEVTAQEBBIPEEWEVKAKOEWADREMXMTBHHCHRTKDNVRZCHRCLQOHPWQAIIWXNRMGWOIIFKEE"
```

```text
length  5  IoC 0.0666  key JANET
  length 10  IoC 0.0663  key JANETJANET
  length 15  IoC 0.0693  key JANETJANTTJANET
  length 20  IoC 0.0604
  length  3  IoC 0.0466
  ...
Kasiski: 12 distances between repeated trigrams; factors dividing the most: 5 (10), 2 (4), 10 (4), 7 (3), 3 (2).
```

That's Example 1.11 from Stinson's Cryptography: Theory and Practice. The test suite checks it. Stinson gets the same column IoC by hand. Five, then decode:

```bash
ciphers decode vigenere "CHREEVOAHM..." --key JANET   # THEALMONDTREEWASINTENTATIVEBLOSSOM...
```

How does it know? For each length from 2 to 20, the letters get dealt into columns. Each column gets its IoC, the length gets their mean. Wrong length, every column mixes alphabets and sits near 0.038. Right length, it jumps to plaintext level. Here 0.047 at 3 against 0.067 at 5. Hard to miss.

Multiples are the trap. Ten columns under a five-letter key are still one alphabet each. They have fewer letters, so their IoC wobbles, often upward. Sort by IoC alone and 20 beats 5 on a short text. So a multiple goes right behind a divisor that reads almost as well. 5, then 10, 15, 20. I ran 300 random keys over README prose. At 200 letters the right length came first 90% of the time. At 400, every time. Plain IoC sorting managed 65%. Under 100 letters it's a coin toss either way.

Kasiski is the second opinion. It finds every trigram that repeats and measures the distance back to its last copy. Then it counts how many distances each factor divides. Why does that work? THE under the same key letters gives the same ciphertext. Those copies sit a multiple of the key length apart. Chance repeats add noise. And 2 always looks good, half of all numbers are even.

The top three lengths get a key. Each column takes the Caesar shift that reads most like the language. Same `fit` the brute force uses. `--lang pl` or `ja` changes the language, `--max-period` the longest length.

```ts
import { estimatePeriod } from "@agntn/ciphers";

const analysis = estimatePeriod(ciphertext, "en", 20);
analysis.periods[0]; // { period: 5, ic: 0.0666, key: "JANET" }
analysis.factors[0]; // { factor: 5, distances: 10 }
```

<table>
<thead>
  <tr>
    <th>
      Field
    </th>
    
    <th>
      Meaning
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        total
      </code>
    </td>
    
    <td>
      A to Z letters, the ones Vigenère shifts
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        periods
      </code>
    </td>
    
    <td>
      <code>
        { period, ic }
      </code>
      
       most likely first, <code>
        key
      </code>
      
       on the top three. Empty below four letters
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        distances
      </code>
    </td>
    
    <td>
      Distances between repeated trigrams
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        factors
      </code>
    </td>
    
    <td>
      <code>
        { factor, distances }
      </code>
      
      , most distances first
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        referenceIc
      </code>
    </td>
    
    <td>
      IoC of plaintext in the language
    </td>
  </tr>
</tbody>
</table>

The key is Vigenère math. Beaufort has the same length but shifts the other way, and `recover` below handles that. Autokey has no length at all. Its key runs on into the plaintext and never repeats. Nothing to find, sorry.

## Recovering the key

`period` guesses each key letter from its own column alone. On a short text a letter or two comes out wrong. `recover` goes the rest of the way. Name the cipher and get keys back, best first:

```bash
ciphers recover "CHREEVOAHM..." --cipher vigenere --limit 2
```

```text
Vigenère keys for 313 letters (lang=en), best fit first. Fit is the mean log probability per quadgram: English plaintext scores about -9.44, random letters -13.95.

1. key JANET, fit -9.82: "THEALMONDTREEWASINTENTATIVEBLOSSOMTHEDAYSWERELONGER..."
2. key MTE, fit -13.41: "QONSLRCHDAHAFHPPPWLESHUTPLACWDPZXETMSXAFISFCTIVWYEWCZTLDAOOXKNFATMAUGUYBJNTKANNE"…
```

Stinson again, JANET again, no decode needed. Fit is the mean log probability of a quadgram, four letters in a row. English sits near -9.4 and random letters near -14. JANET reads. MTE is noise. That gap is the whole verdict.

How does it get there? It tries the five likeliest lengths. Each column first takes the shift whose letter counts fit best by chi-squared. Then quadgrams take over: change one key letter, then two neighbours at once, keep whatever reads better. Why pairs? A quadgram spans neighbouring columns, so two wrong letters can hold each other in place. `--cipher beaufort` and `--cipher variant-beaufort` run the same search with the shift going the other way. Know the length already? `--period` skips the guessing.

A substitution has no length, just 26! alphabets. So it climbs. Swap two letters, keep the swap if the text reads better, stop when no swap helps. Then start over from a random alphabet, up to a hundred times. Short texts get the most restarts, they're cheap.

```bash
ciphers recover "Nih. Sfwhlm yilftsg rm gsv gizb zg vrtsg. Slonvh zgv mlgsrmt, ivzw gsv mlgv gdrxv zmw gsivd rg rmgl gsv uriv drgslfg z dliw." --cipher substitution --limit 2
```

```text
1. key ZYXWVUTSR??NBMLO?IHGF?D???, fit -9.21: "Lrs. Hudson brought in the tram at eight. Hoples ate nothing, read the note twice and threw it into the fire without a word."
2. key ZYXWVUTSR??OBML??IHGFND???, fit -9.23: "Vrs. Hudson brought in the tram at eight. Holves ate nothing, read the note twic"…
```

That's Atbash on 97 letters. Close, not perfect. M, L and Y show up once or twice each, and "tram" reads as well as "tray". Your eyes fix the rest. More text fixes it for you. On ten 150-letter passages from Sherlock Holmes, every one came back with at least 95% of its letters right. The key gives the cipher letter for each plaintext letter A to Z, and `?` marks a letter the text never uses. Holes and all, it goes straight into `ciphers decode substitution --key`.

Columnar is plain brute force. Every column order of every width from 2 to 8, scored on the start of the text, about a tenth of a second. `--key-length 9` adds 362,880 more orders and takes under a second.

```bash
ciphers recover "ru gn  i eeh  nt t nhrt rMHnuieye.mtt,d  e witiito.srttrtho nnehtinrto  o .sdbh tagHs irtowahiteehad oo ha tlaogaeecde  fwuw" --cipher columnar --limit 1
# 1. key BADCE, fit -9.30: "Mrs. Hudson brought in the tray at eight. Holmes ate nothing, ..."
```

The text went in under BAKER. BADCE is BAKER in disguise: columnar only cares about the alphabetical order of the letters, and that order is the same. `ciphers decode columnar "<text>" --key BADCE` takes it as is.

Homophonic substitution gives one letter several symbols. Feed `recover` symbols separated by spaces or commas. The agent tool `ciphers_key_recover` accepts `cipher: "homophonic"` too.

```bash
ciphers recover - --cipher homophonic --limit 2 < letter.txt
```

Got two-digit numbers without separators? Use `--symbol-width 2`, or `symbolWidth: 2` in the library. Widths range from 1 to 8 characters. Spaces and commas are skipped. Leftover characters make the input invalid.

```ts
import { recoverKey } from "@agntn/ciphers";

const recovery = recoverKey("10 15 43 11 62 21 49 52 63 17 48 29 26 54 39 20 ...", { cipher: "homophonic" });
recovery.candidates[0].text; // "TOSHERLOCKHOLMESSHEISALWAYSTHEWOMANIHAVESELDOMHEARD..."
recovery.candidates[0].key; // "A=36 13 50 27, B=19, C=63 40, D=37 14, E=62 39 16 53 30 67 44, ..."
recovery.candidates[0].map["10"]; // "T"
recovery.randomFit; // -11.05…
```

The search uses English quadgrams and simulated annealing. It changes one symbol's letter at a time. Early on, it sometimes accepts a worse map. That chance cools to zero. Eight random starts use a fixed seed, so results repeat. A built-in chi-squared penalty checks letter counts against English. Without it, E, T and A hog the symbols.

The key groups symbols under their plaintext letters. Unused letters don't appear. `map` looks up each symbol, and `text` has one letter per symbol, without spaces. The first two paragraphs of *A Scandal in Bohemia* make 772 letters. Encoded with 60 symbols, recovery got 770 right. Symbol 42 appeared twice and came back as N both times.

The top key scored -9.55, close to the English reference of -9.44. But a many-to-one map can squeeze English out of noise. Random symbols land around -11, not -13.95. That's why `randomFit` runs the same search on shuffled symbols. Here it scored -11.06.

Real English lands 1 to 2 above that bar. The second candidate scored -10.93, right next to it. That's noise pretending to read.

Give it around 600 symbols. At roughly 330, local runs recovered about half the letters. More symbols per letter need more text. At roughly 650 letters, 90 symbols gave 90 to 97% accuracy. With 50 symbols, it was over 99%.

A local run of roughly 770 symbols took about a second. Results contain five candidates by default, never more than the starts, and up to 20 through `--limit`.

All keys near misses? Roll the maps again. Use `--starts` and `--seed`, or `starts` and `seed` in the library. The same text and seed repeat the keys. Another seed changes the starting maps. With the same seed, 16 starts include the first 8 keys.

Twice the starts take twice the time. The CLI and agent tool cap starts at 32 because the `/mcp` worker has a CPU limit.

```bash
ciphers recover - --cipher homophonic --starts 24 --seed 7 < letter.txt
```

Got a way to recognize words? Pass a `score` function in the library. It receives uppercase plaintext without spaces and returns a number. That's added to the quadgram fit, in nats per quadgram. The search asks at every step, so the score steers it. Keep it cheap. Result `fit` stays the plain quadgram fit.

```ts
import { recoverKey } from "@agntn/ciphers";

const words = ["THE", "AND", "THAT", "WITH", "HAVE"];
const hits = (plain: string) => words.reduce((sum, word) => sum + plain.split(word).length - 1, 0);

const recovery = recoverKey("10 15 43 11 62 21 49 52 63 17 48 29 26 54 39 20 ...", {
  cipher: "homophonic",
  starts: 24,
  seed: 7,
  score: (plain) => (2 * hits(plain)) / plain.length,
});
```

The letter count penalty still pushes back. A timid score can change nothing. That's a weight problem, not a word model. A score returning NaN or Infinity is refused.

The quadgrams come from ten Project Gutenberg novels, Dickens to Tolstoy, 7.86 million of them with spaces dropped. The 16,000 most common made the cut. The full Google Books table counts inside words only, and it solved none of twelve test texts once the spaces were gone. Puzzles drop spaces all the time.

Polish or Japanese romaji? There's no quadgram table for those yet, so `--lang pl` scores single letters. That's enough for Vigenère and both Beauforts, every column is its own Caesar. A longer key pays ln 26 per letter there, or twelve columns beat six by pure chance. Substitution, columnar and homophonic need English.

```ts
import { recoverKey } from "@agntn/ciphers";

const recovery = recoverKey(ciphertext, { cipher: "vigenere" });
recovery.candidates[0]; // { key: "JANET", fit: -9.82…, text: "THEALMONDTREE..." }
```

<table>
<thead>
  <tr>
    <th>
      Field
    </th>
    
    <th>
      Meaning
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        candidates
      </code>
    </td>
    
    <td>
      <code>
        { key, fit, text }
      </code>
      
      , best first, five unless <code>
        limit
      </code>
      
       says otherwise. Homophonic adds <code>
        map
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        scoredBy
      </code>
    </td>
    
    <td>
      <code>
        quadgrams
      </code>
      
       for English, <code>
        letters
      </code>
      
       for Polish and Japanese romaji
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        referenceFit
      </code>
    </td>
    
    <td>
      Fit of plaintext in the language
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        randomFit
      </code>
    </td>
    
    <td>
      Fit of random letters. For homophonic, of the same symbols shuffled
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        letters
      </code>
    </td>
    
    <td>
      A to Z letters in the text, or symbols for homophonic
    </td>
  </tr>
</tbody>
</table>

`ciphers_key_recover` does the same for a model. Only the top text comes back whole, the rest stop at 80 characters.

## Scoring your own decoding

`recover` searches only the ciphers it knows. A route traced by hand or your own hill climb needs a verdict too. That's what `scoreQuadgrams` gives it.

```ts
import { scoreQuadgrams } from "@agntn/ciphers";

scoreQuadgrams("Mrs. Hudson brought in the tray at eight. Holmes ate nothing.");
// { letters: 48, fit: -9.888…, referenceFit: -9.44, randomFit: -13.952… }
```

Same letters in, same number out as `recoverKey` puts next to that text, to the last digit. Case, spaces and punctuation don't count. Under four letters there's no quadgram to score, so it's `undefined`. English only, like the table.

It's a fit, not a spell checker. The Atbash near miss from above, `Lrs. Hudson` with the tram and `Hoples`, keeps its -9.21. The sentence Doyle could have written, tray and Holmes intact, gets -9.30 and loses. Both sit far from -13.95, and that's the gap that matters.

`ciphers frequency` prints the same number under the IC for English text, and so does `ciphers_frequency`. A model checks its own decoding without a second tool.

## Which passphrase settings?

A blob that starts with `U2FsdGVkX1` is a [passphrase blob](https://ciphers.agntn.dev/ciphers/aes-passphrase). You have the passphrase. You don't have the rest. MD5 or SHA-256? 128 bits or 256? One hash pass or ten thousand? The header won't tell you. So try them all:

```bash
ciphers probe "U2FsdGVkX18HYWQDuJcJTh2NoqzqwZ9pWaEBkXGGu54=" --key secret --iterations '[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]'
```

```text
Passphrase probe (salt 07616403b897094e, 1 block, 144 tries: digests md5, sha1, sha256 × keyLength 128, 192, 256 × iterations 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16):
Padding held in 2 of 144 tries, about 0.56 expected by chance. Most printable first:

  digest sha256, keyLength 256, iterations 1: pad 2, 100% printable, "ATTACK AT DAWN"
  digest md5, keyLength 192, iterations 13: pad 1, 33% printable, not UTF-8, hex 4232d77f248ed9f9e107f42fc46ab8

A wrong setting passes the padding check about once in 255 tries, ...
```

Two hits. One of them is real. The blob comes from `openssl enc -md sha256`, the same one the test suite opens. The MD5 line is luck. A wrong key ends in a valid `01` pad once in 256 tries. Add the rarer `02 02` and longer, and it's one in 255. Run 144 tries and half a hit falls out of thin air. Run a few hundred and you get a couple. That's why the count sits next to the hits.

How do you tell them apart? The real one reads. Noise is bytes that aren't UTF-8, usually less than half of them printable, and its pad is 1 nearly every time. The list goes most printable first, so the answer is on top.

It's cheap, too. Each digest and iteration count runs `EVP_BytesToKey` once, and every key length is a slice of that same output. Only the last block gets decrypted until its padding holds. Without flags you get md5, sha1 and sha256 at 128, 192 and 256 bits, one iteration. Nine tries. `--digests` and `--key-lengths` take JSON arrays too, like `'["md5","sha256"]'`. The iteration counts add up to at most a million hash passes across the digests.

Nothing at all? Wrong passphrase, or a setting outside the grid. Or `openssl enc -pbkdf2`, which writes the same header but derives the key with PBKDF2. This format doesn't take that.

```ts
import { probePassphrase } from "@agntn/ciphers";

const probe = probePassphrase(blob, "secret", { iterations: [1, 1000, 10000] });
probe.hits[0]; // { digest: "sha256", keyLength: 256, iterations: 1, padLength: 2, printable: 1, text: "ATTACK AT DAWN", ... }
probe.expected; // 0.106 for 27 tries
```

<table>
<thead>
  <tr>
    <th>
      Field
    </th>
    
    <th>
      Meaning
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        hits
      </code>
    </td>
    
    <td>
      Settings whose padding held, most printable first
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        tries
      </code>
    </td>
    
    <td>
      Digests times key lengths times iteration counts
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        expected
      </code>
    </td>
    
    <td>
      Padding hits a wrong passphrase gives over that many tries
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        padLength
      </code>
    </td>
    
    <td>
      1 to 16. Noise lands on 1 in 255 of 256 cases
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        printable
      </code>
    </td>
    
    <td>
      Share of the characters that print, 0 to 1
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        text
      </code>
      
      , <code>
        hex
      </code>
    </td>
    
    <td>
      The plaintext, <code>
        text
      </code>
      
       only when it's UTF-8
    </td>
  </tr>
</tbody>
</table>

## Crib dragging a reused key

One key, two messages. That's the end of the one-time pad. XOR the two ciphertexts and the key cancels out. What's left is one plaintext XOR the other. Guess a word in one, and the other shows through under it.

The guess is the crib. Dragging means trying it at every byte. Here are three ciphertexts from Dan Boneh's Many Time Pad exercise, all under one key:

```bash
ciphers crib '["315c4eeaa8b5f8aa…","234c02ecbbfbafa3…","32510ba9babebbbe…"]' --crib " the " --limit 5
```

```text
Crib " the " across 3 ciphertexts (lang=en), 299 places, most readable first:

1. #0 at 70 (score -2.76): #1 " of c", #2 "ore t"
2. #2 at 60 (score -2.89): #0 "lso f", #1 "rner "
3. #1 at 35 (score -3.21): #0 "arucm", #2 " oude"
4. #2 at 70 (score -3.32): #0 "ore t", #1 "oike7"
5. #0 at 13 (score -3.32): #1 "robab", #2 "ssage"
(294 more places ranked lower)
```

`#0 at 70` puts the crib in ciphertext 0 from byte 70. Under that guess the other two read `" of c"` and `"ore t"`. That's English. Lines 2 and 5 too. Line 3 is junk, nobody writes `arucm`. The score is the mean log probability of the revealed bytes as text: spaces and common letters score high, control bytes sink. Ciphertexts and bytes count from 0.

Found one that reads? Accept it:

```bash
ciphers crib '["315c4eea…","234c02ec…","32510ba9…"]' --crib "ssage" \
  --known '[{"message":0,"offset":70,"text":" the "}]'
```

Accepted places fix key bytes. A place that disagrees with them drops out, and so does one that only repeats them. Every call prints the key so far and each plaintext, with `·` where nothing is known yet. Then `ssage` turns out to sit in ciphertext 2 at 13, and ciphertext 0 reads `the` there. A plaintext grows a few bytes per call, and a half known word begs for a longer crib.

Got only two ciphertexts? Then every place shows up twice. The crib in #0 reveals #1, the crib in #1 reveals #0, same bytes. Which side is it on? Two can't tell you. A third one can, the wrong side reveals junk there.

`ciphers_crib_drag` does the same for a model. `known` is an argument, so the drag lives in the calls, not in a server. One accepted place per call.

```ts
import { dragCrib, showCribBytes } from "@agntn/ciphers";

const drag = dragCrib([first, second, target], { crib: " the ", limit: 5 });
drag.candidates[0]; // { message: 0, offset: 70, score: -2.76…, reveals: [...] }
showCribBytes(drag.candidates[0].reveals[1].bytes); // "ore t"
```

<table>
<thead>
  <tr>
    <th>
      Field
    </th>
    
    <th>
      Meaning
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        total
      </code>
    </td>
    
    <td>
      Places that reveal a byte and agree with <code>
        known
      </code>
      
      , ranked or not
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        candidates
      </code>
    </td>
    
    <td>
      <code>
        { message, offset, score, reveals }
      </code>
      
      , the top <code>
        limit
      </code>
      
      , most readable first
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        key
      </code>
    </td>
    
    <td>
      One byte per position of the longest ciphertext, <code>
        undefined
      </code>
      
       where nothing fixes it
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        plaintexts
      </code>
    </td>
    
    <td>
      Each ciphertext under that key, <code>
        undefined
      </code>
      
       where the key is unknown
    </td>
  </tr>
</tbody>
</table>

`showCribBytes` prints bytes the way the command does: text as text, anything else as `\xNN`, unknown as `·`. This is why a one-time pad gets used one time.

## Hidden in plain sight

Some messages aren't encrypted at all. They sit in the text, one letter per line or per word, and the text around them is a decoy. Here's a German telegram from 1917, the one Kahn tells in The Codebreakers:

```bash
ciphers hidden "PRESIDENT'S EMBARGO RULING SHOULD HAVE IMMEDIATE NOTICE. GRAVE SITUATION AFFECTING INTERNATIONAL LAW. STATEMENT FORESHADOWS RUIN OF MANY NEUTRALS. YELLOW JOURNALS UNIFYING NATIONAL EXCITEMENT IMMENSELY."
```

```text
Hidden text readings (68 tried, 57 with 5 or more A-Z letters, lang=en), most like the language first:

   0.19  pick=word letter=1 -> PERSHINGSAILSFROMNYJUNEI
  -0.07  pick=every-letter every=8 start=4 -> SMLLMOVITRLEERNLJUNENE
  -0.08  pick=every-letter every=9 start=7 -> EGHINVONTSFWALOIITE
  ...
```

Pershing sails from NY June 1. First letter of every word.

Without `--pick` the command tries the usual places. The first, second and last letter of each line, word, sentence and paragraph. Both diagonals. Every nth letter for n up to 10, from every start. That's 68 readings. A reading with fewer than five letters A to Z is dropped, a short one fits anything by chance. The rest get ranked.

How? Not by single letters. Every second letter of English prose has the same letters as English, just in the wrong order. So the ranking looks at pairs. It takes how often a pair shows up in English, against how often its two letters would meet by chance. The mean over the reading is the number on the left. Above 0 the pairs read like English. Near 0 or below, the letters were picked at random. The opening of A Tale of Two Cities hides nothing, and its best reading stays below 0.

Polish and Japanese have no pair table yet. With `--lang pl` or `ja` the readings rank by `fit`, single letters, and the number goes away. Read past the top line there.

Every nth word is never ranked. Words taken out of a text read like the language whether they hide something or not. So that one you ask for:

```bash
ciphers hidden "SALUDOS LOVED ONE SO TODAY I HEARD FROM UNCLE MOE ..." --pick every-word --every 5 --start 5
# TODAY MOE TOLD ME HE TESTED POSITIVE FOR METHAMPHETAMINES
```

That's a prison letter the FBI published in 2011. `--pick` reads one place and prints only that. `line`, `word`, `sentence` and `paragraph` take `--letter`, 1 for the first, -1 for the last. `every-letter` and `every-word` take `--every` and `--start`. `diagonal` takes `--start` and `--direction down-left`, which counts from the end of each line.

Only letters count. Spaces, digits and punctuation are never picked, and a line with no letters is skipped. That matters for Poe's A Valentine. The first letter of line one, the second of line two and so on spell Frances Sargent Osgood, but only if you count letters, not characters. And the closing poem of Through the Looking-Glass spells Alice Pleasance Liddell down its lines, which the ranking puts first.

```ts
import { readHiddenText, rankHiddenText } from "@agntn/ciphers";

readHiddenText(poem, { pick: "diagonal" }); // "Francessargentosgood"
rankHiddenText(carroll).candidates[0].text; // "ALICEPLEASANCELIDDELL"
```

## Invisible and lookalike characters

### Is that really Bitcoin?

Text can look familiar and still contain different characters. Got a word that hashes wrong? One Cyrillic letter or zero-width space changes the hash. It also changes any password derived from that text.

```bash
ciphers inspect "Bitcоin"
```

```text
1 of 7 characters are not what they seem, held against Latin:

  U+043E CYRILLIC SMALL LETTER O (Cyrillic) looks like "o" at 5

Words that mix scripts:
  "Bitcоin" at 1: Latin and Cyrillic, skeleton "Bitcoin"

In order: U+043E
As the ASCII they pass for: "o"
```

That word reads Bitcoin, but it isn't Bitcoin. The `o` is Cyrillic.

`inspect` reports four kinds: invisible characters, lookalikes, combining marks and letters from another script. Invisible characters include spaces other than the plain one. Lookalikes include styled letters and curly quotes.

Positions count code points from 1. Invisible characters appear as `U+XXXX`, never raw. Emoji joiners and variation selectors are left alone. Tabs and line breaks are ordinary.

The command guesses the main script from the letters. Use `--script Cyrillic` to override it. In Cyrillic text, a stray Latin `a` is odd.

Mixed words also get a Unicode skeleton. It's for comparison, not display. The skeleton folds `m` into `rn` and `1` into `l`.

```bash
ciphers inspect "pаypal.com раураl"
```

```text
6 of 17 characters are not what they seem, held against Latin:

  U+0430 CYRILLIC SMALL LETTER A (Cyrillic) looks like "a" 3 times at 2, 13, 16
  U+0440 CYRILLIC SMALL LETTER ER (Cyrillic) looks like "p" 2 times at 12, 15
  U+0443 CYRILLIC SMALL LETTER U (Cyrillic) looks like "y" at 14

Words that mix scripts:
  "pаypal.com" at 1: Latin and Cyrillic, skeleton "paypal.corn"
  "раураl" at 12: Cyrillic and Latin, skeleton "paypal"

In order: U+0430 U+0440 U+0430 U+0443 U+0440 U+0430
As the ASCII they pass for: "apaypa"
```

### Invisible ink in a text file

Want to leave a note nobody can see? `conceal` puts it after the cover's first character. The default scheme is `binary`.

```bash
ciphers conceal "meet at noon" --cover "Nothing to see here." > note.txt
ciphers inspect - < note.txt
```

```text
96 of 117 characters are not what they seem, held against Latin:

  U+200B ZERO WIDTH SPACE invisible 48 times at 2, 5, 8, 10, 13, 14, 16, 18 and 40 more
  U+200C ZERO WIDTH NON-JOINER invisible 48 times at 3, 4, 6, 7, 9, 11, 12, 15 and 40 more

The invisible ones spell "meet at noon" with scheme=binary; ciphers_zero_width_read reads it whole.
```

That's 96 characters nobody can see. `reveal` tries the built-in schemes and lists readings that produce text.

```bash
ciphers reveal - < note.txt
```

```text
Zero-width readings (5 schemes tried, 1 read as text), printable ASCII first:

  scheme=binary -> "meet at noon"
```

Choose a scheme to print only its message.

```bash
ciphers reveal - --scheme binary < note.txt
```

```text
meet at noon
```

Without `--cover`, `conceal` returns bare invisible characters. It refuses a cover containing characters from the chosen scheme. That includes a U+200D emoji joiner when the scheme uses it.

### Pick a scheme

Each character is a digit. The digits encode bytes or code points.

<table>
<thead>
  <tr>
    <th>
      Scheme
    </th>
    
    <th>
      Characters
    </th>
    
    <th>
      How it counts
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        binary
      </code>
    </td>
    
    <td>
      U+200B, U+200C
    </td>
    
    <td>
      Eight binary digits per UTF-8 byte
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        330k
      </code>
    </td>
    
    <td>
      Four characters
    </td>
    
    <td>
      Eight base 4 digits per UTF-16 code unit
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        zwsp-steg
      </code>
    </td>
    
    <td>
      Five characters
    </td>
    
    <td>
      Seven base 5 digits per code point
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        zero-width-lib
      </code>
    </td>
    
    <td>
      Five characters
    </td>
    
    <td>
      Base 5, with a zero-width space between characters
    </td>
  </tr>
</tbody>
</table>

The last three match their original tools character for character. The library reads their output too. Ranking also tries `binary` with the digits swapped.

Need your own alphabet? Pass symbols in digit order with `--symbols "U+200C U+200B" --digits 8`. Use `--separator U+200D` for numbers of any length. Set `--unit` to `byte`, `code-unit` or `code-point`. The default is `byte`.

Symbols don't have to be invisible. `--symbols "U+0020 U+0009" --digits 8` reads spaces and tabs as bits. Leftover characters suggest another scheme or lost characters. Sites and chat apps often strip invisible characters.

The library exposes the same operations:

```ts
import {
  confusableSkeleton,
  hideZeroWidth,
  inspectCharacters,
  rankZeroWidth,
  readZeroWidth,
} from "@agntn/ciphers";

const character = inspectCharacters("Bitcоin").characters[0];
// codePoint: 0x43e, position: 5, kind: "lookalike"
// script: "Cyrillic", name: "CYRILLIC SMALL LETTER O", lookalike: "o"

confusableSkeleton("Bitcоin") === confusableSkeleton("Bitcoin"); // true

const note = hideZeroWidth("meet at noon", {
  scheme: "binary",
  cover: "Nothing to see here.",
});
readZeroWidth(note, { scheme: "binary" }); // "meet at noon"
rankZeroWidth(note).candidates[0].name; // "binary"
```

## Messages in ordinary whitespace

Spaces, tabs and line endings can carry bits. Their positions matter. `whitespace` lists what it finds, then reads a channel when you supply a mapping.

### How do I plant a message at line ends?

Got a text file with four lines? Use it as a cover for a known message. This gives you something to look for when you read the file.

```bash
ciphers trail "noon" --cover - --zero space --one tab < poem.txt > note.txt
```

`trail` puts one space or tab per bit at line ends. It starts on the first line and uses eight bits per line by default. Set `--per-line` to change that, up to 64.

A cover needs enough lines. It also can't have lines that already end in spaces or tabs. `trail` refuses both cases rather than changing existing whitespace.

Cover text and line endings stay untouched. The terminal prints every line ending as LF, though. Use `--json` to keep the cover's own CR.

### Where does the whitespace sit?

Ask for an inventory before choosing a mapping.

```bash
ciphers whitespace - < note.txt
```

```text
4 lines. Spaces, tabs and line endings by position:

  line-ending: 4 (lf 4)
  trailing: 4 (mixed 4)
    mixed at line 1, column 15 [14,22), 1 space + 2 tabs + 1 space + 3 tabs + 1 space
    mixed at line 2, column 18 [40,48), 1 space + 2 tabs + 1 space + 4 tabs
    mixed at line 3, column 21 [69,77), 1 space + 2 tabs + 1 space + 4 tabs
    mixed at line 4, column 17 [94,102), 1 space + 2 tabs + 1 space + 3 tabs + 1 space
  interior: 9 (single 9)
  sentence: none

Places are line and column from 1, then [start,end) as UTF-16 offsets. Single spaces and the usual line ending are counted, not listed; pass channel to list one channel whole.
This is what is there, not a sign that anything is hidden. To read a channel as bits pass channel with zero and one, such as channel trailing, zero space, one tab.
```

The inventory counts every class, then lists places that stand out. That's observation, not evidence of a secret. Pass `--channel` alone to list that channel whole.

Each channel lists up to 20 places. The rest are counted. Lines and columns start at 1. Offsets are `[start,end)` in UTF-16 and work with `slice`. Nothing gets trimmed or normalized.

<table>
<thead>
  <tr>
    <th>
      Channel
    </th>
    
    <th>
      Classes
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        line-ending
      </code>
    </td>
    
    <td>
      <code>
        lf
      </code>
      
      , <code>
        crlf
      </code>
      
      , <code>
        cr
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        trailing
      </code>
    </td>
    
    <td>
      <code>
        space
      </code>
      
      , <code>
        tab
      </code>
      
      , one character at a time
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        interior
      </code>
    </td>
    
    <td>
      <code>
        single
      </code>
      
      , <code>
        double
      </code>
      
      , <code>
        wide
      </code>
      
      , <code>
        tab
      </code>
      
      , <code>
        mixed
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        sentence
      </code>
    </td>
    
    <td>
      <code>
        single
      </code>
      
      , <code>
        double
      </code>
      
      , <code>
        wide
      </code>
      
      , <code>
        tab
      </code>
      
      , <code>
        mixed
      </code>
    </td>
  </tr>
</tbody>
</table>

Trailing whitespace includes the last line, even without a line ending. Interior gaps sit between visible characters. Sentence gaps follow `.`, `!` or `?`. Set `--boundaries` for other preceding characters. There's no language guessing.

Only ordinary spaces, tabs, CR and LF count. Indentation is left alone. For no-break spaces and zero-width characters, use `inspect` and `reveal`.

### How do I read whitespace as bits?

Choose a channel and say which classes mean zero and one. Nothing guesses that mapping.

```bash
ciphers whitespace - --channel trailing --zero space --one tab < note.txt
```

```text
trailing: 32 bits, space as 0 and tab as 1.
Bits: 01101110011011110110111101101110
4 groups of 8 bits as byte, msb first: "noon"
```

The poem says nothing to see here. Its line ends say `noon`.

Swap the classes to try the other polarity.

```bash
ciphers whitespace - --channel trailing --zero tab --one space < note.txt
```

```text
trailing: 32 bits, tab as 0 and space as 1.
Bits: 10010001100100001001000010010001
4 groups of 8 bits as byte, msb first: no text. The hidden bytes are not UTF-8
```

A class without a bit stops the reading.

```bash
ciphers whitespace "a  b c   d" --channel interior --zero single --one double
```

```text
1 interior place has no bit in the mapping: wide. The first is at line 1, column 7. Map every class in zero or one, or set unmapped to skip to leave them out
```

Use `--unmapped skip` to leave those places out. They're still listed.

```bash
ciphers whitespace "a  b c   d" --channel interior --zero single --one double --unmapped skip
```

```text
interior: 2 bits, single as 0 and double as 1.
Bits: 10
0 groups of 8 bits as byte, msb first: ""
2 bits left over after the last whole group: 10
Left out 1 place the mapping gives no bit: wide at line 1, column 7 [6,9), 3 spaces
```

Groups default to eight bits, most significant bit first, as UTF-8 bytes. Use `--digits`, `--order`, `--unit` and `--offset` to change the reading. Leftover bits aren't dropped.

`reveal --symbols "U+0020 U+0009"` reads spaces and tabs wherever they sit. Use `whitespace` when their position matters.

### How do I use this from the library?

The same poem can carry the same message through the library.

```ts
import { hideWhitespace, inspectWhitespace, readWhitespace } from "@agntn/ciphers";

const poem = "Roses are red,\nviolets are blue,\nnothing to see here,\nmove along, you.\n";
const note = hideWhitespace("noon", { cover: poem, zero: ["space"], one: ["tab"] });

inspectWhitespace(note, { channels: ["trailing"] }).channels[0].occurrences[0];
// { channel: "trailing", class: "mixed", start: 14, end: 22, line: 1, column: 15, raw: " \t\t \t\t\t ", count: 8 }

readWhitespace(note, { channel: "trailing", zero: ["space"], one: ["tab"] });
// text: "noon", bits: 32 of them, partial: ""
```

Trailing whitespace is a fragile hiding place. Editors, formatters and chat boxes can strip it. Keep the original file when you need to read it.

## Compare two versions of text

### Which words changed?

Got two copies of a clue? Line them up before trusting the repost.

```bash
ciphers align "red fox sleeps" "red fox runs"
```

```text
3 tokens against 3, cut as words and compared exact: 2 equal, 1 replaced, 0 inserted, 0 deleted.

  equal    left 0-2 [0,7)  right 0-2 [0,7)  "red fox"
  replace  left 2-3 [8,14)  right 2-3 [8,12)  "sleeps" -> "runs"

Token ranges count from 0 and stop before the second number. [start,end) are UTF-16 offsets into each text.
```

The first two words match. The last word changed.

`align` cuts both texts into tokens. The default `--tokens words` takes runs of letters, combining marks and digits. Punctuation and whitespace fall between tokens. With `--tokens whitespace`, punctuation stays inside each token.

The rows cover every token in order. `equal` pairs matching tokens. Between matched runs, `replace` holds tokens from both sides. `insert` holds only right tokens. `delete` holds only left tokens.

Token ranges start at 0 and exclude the second number. Offsets are UTF-16 positions for `text.slice(start, end)`. An empty range sits where the preceding token ends.

### What counts as a match?

```bash
ciphers align "The key is under the old oak, at dawn." "the key is under the oak at Dawn, friend" --compare caseless
```

```text
9 tokens against 9, cut as words and compared caseless: 8 equal, 0 replaced, 1 inserted, 1 deleted.

  equal    left 0-1 [0,3)  right 0-1 [0,3)  "The" = "the"
  equal    left 1-5 [4,20)  right 1-5 [4,20)  "key is under the"
  delete   left 5-6 [21,24)  right 5-5 [20,20)  - "old"
  equal    left 6-8 [25,32)  right 5-7 [21,27)  "oak, at"
  equal    left 8-9 [33,37)  right 7-8 [28,32)  "dawn" = "Dawn"
  insert   left 9-9 [37,37)  right 8-9 [34,40)  + "friend"

Token ranges count from 0 and stop before the second number. [start,end) are UTF-16 offsets into each text.
A row with = holds tokens that match only as compared (caseless).
```

`old` is gone and `friend` appears. The `=` rows match after ignoring case.

`--compare exact` is the default. `canonical` uses NFC, so separate combining marks match precomposed letters. `caseless` also uses lower case. `unaccented` drops combining marks after that. Polish ł has no combining mark, so it stays.

### Can the pairing be trusted?

```bash
ciphers align "to be or not to be" "to be"
```

```text
6 tokens against 2, cut as words and compared exact: 2 equal, 0 replaced, 0 inserted, 4 deleted.

  equal    left 0-2 [0,5)  right 0-2 [0,5)  "to be"  (ambiguous)
  delete   left 2-6 [6,18)  right 2-2 [5,5)  - "or not to be"

Token ranges count from 0 and stop before the second number. [start,end) are UTF-16 offsets into each text.
A row marked ambiguous has a repeated word: another alignment with as many equal tokens pairs it otherwise.
```

There are two honest answers to `to be`. The marked row tells you the pairing isn't certain.

The aligner seeks the longest common subsequence. That's the pairing with the most matching tokens. If another such pairing pairs a token differently, the row is ambiguous. On a tie, the left token is dropped first. The choice is repeatable, not proof of intent.

```bash
ciphers align "Stop, thief!" "Stop thief"
```

```text
2 tokens against 2, cut as words and compared exact: 2 equal, 0 replaced, 0 inserted, 0 deleted.

  equal    left 0-2 [0,11)  right 0-2 [0,10)  "Stop, thief"

Token ranges count from 0 and stop before the second number. [start,end) are UTF-16 offsets into each text.
Every token matches, yet the texts differ: look at the whitespace and punctuation between them, which is never compared.
```

The thief lost his punctuation, not his words. Matching tokens don't make the texts identical.

Whitespace and punctuation between tokens aren't compared. The library returns them as `separators` beside `tokens`. Both have `raw`, `start` and `end`. Together they cover every character exactly once.

### Checking a map

Wrote or edited rows yourself? Pass them with `--rows` instead of aligning.

```bash
ciphers align "red fox sleeps" "red fox runs" \
  --rows '[{"operation":"equal","left":{"from":0,"to":3},"right":{"from":0,"to":3}}]'
```

```text
The rows do not hold against 3 left and 3 right tokens, 1 problem:

  /rows/0 equality: left token 2 does not equal its partner
```

The claimed equality doesn't hold. A bad map is an answer, not an error. The command exits with code 0 and lists problems by JSON pointer.

Each row has an `operation` and `left` and `right` ranges. Each range has `from` and `to`. The check reports gaps, overlaps, wrong order and ranges past the end. It also catches wrong token counts and false equalities.

Use `alignTexts` and `checkAlignment` from the library:

```ts
import { alignTexts, checkAlignment } from "@agntn/ciphers";

const texts = { left: "red fox sleeps", right: "Red fox runs" };
const map = alignTexts(texts, { compare: "caseless" });

map.rows[0];
// { operation: "equal", left: { from: 0, to: 1, start: 0, end: 3 },
//   right: { from: 0, to: 1, start: 0, end: 3 }, exact: false, ambiguous: false }

checkAlignment(texts, map).valid; // true

const edited = { ...map, rows: [{ ...map.rows[0], exact: true }, ...map.rows.slice(1)] };
checkAlignment(texts, edited).problems;
// [{ code: "equality", at: "/rows/0", message: "exact is false for these tokens" }]
```

`exact: false` records a match made by comparison. The check catches the edited claim of exact equality.

`checkAlignment(texts, map)` returns `{ valid, problems, count }`. It checks tokens and separators against the source texts. Tokens have to sit where `tokens` cuts the text. A map can't tuck a changed word in between them. It checks rows against tokens and equalities against each pair. It doesn't check `ambiguous`. That's the aligner's remark on its own choice.

Only have rows to check? `tokenizeTexts(texts, options)` cuts both texts without pairing anything. Put your rows next to its result and hand that to `checkAlignment`. That's what `--rows` does, so the table limit doesn't apply to a check.

### Limits

The comparison table is capped at 4,000,000 cells. That's left tokens plus one, times right tokens plus one. It's about 2,000 words against 2,000.

The CLI and agent tool list at most 500 rows. Past either limit, the call is refused. Align one section at a time. A half map pretending to be whole is worse than no map.

`align` lives beside hidden text analysis. It isn't a cipher and isn't in the cipher registry.


## Sitemap

See the full [sitemap](https://ciphers.agntn.dev/sitemap.md) for all pages.
