Affine cipher solver
Brute-force every valid affine key pair and rank the 312 candidate decryptions by English-likeness.
Open in ctfpalThe affine cipher maps each letter through E(x) = (a*x + b) mod 26. It generalises Caesar (which is a = 1) and Atbash (a = 25, b = 25). Decryption needs the modular inverse of a, which only exists when a is coprime to 26 - so a is restricted to 12 values, and with 26 choices of b the entire keyspace is 312 pairs.
312 keys is not a search, it is a list
Because the keyspace is so small, there is no cleverness required: decrypt under all 312 keys, score each with chi-squared, sort. The correct plaintext is essentially always first for texts over about 40 letters. The only subtlety is that a must be invertible - trying a = 2 produces a many-to-one mapping that cannot be decrypted at all.
- Valid
avalues mod 26: 1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25. a = 1reduces to a Caesar shift byb.a = 25, b = 25is Atbash.- Challenges over a 36- or 95-character alphabet change which
avalues are legal - the coprimality condition is against the alphabet size, not always 26.
Worked example
Affine with a=5, b=8
Input
AFFINE CIPHERResult
IHHWVC SWFRCP (encrypting direction, a=5 b=8)Shown in the encrypt direction because the classic worked example runs that way.
Load this example in the workspaceGo deeper
- Chi-squared, index of coincidence, and why classical ciphers fallCaesar, Vigenere, and substitution ciphers do not need guesswork - they need two statistics. How chi-squared scores a candidate plaintext, how the index of coincidence recovers a key length, and how to combine them into an attack that runs in milliseconds.
Related tools
Caesar cipher decoder with automatic shift detection
Break a Caesar shift without guessing. ctfpal scores all 26 rotations by chi-squared letter frequency and puts the English one first.
Atbash cipher decoder
Decode Atbash, the keyless substitution that maps A to Z, B to Y, and so on. Its own inverse.
Monoalphabetic substitution cipher solver
Break an arbitrary substitution cipher automatically by hill-climbing on quadgram statistics - no key, no guessing.
Modular arithmetic and number theory toolkit
Modular inverse, Chinese remainder theorem, Tonelli-Shanks square roots, Jacobi symbols, and integer nth roots - arbitrary precision, in the browser.