Skip to content
All tools
Classical cryptoRuns locallyNo account

Affine cipher solver

Brute-force every valid affine key pair and rank the 312 candidate decryptions by English-likeness.

Open in ctfpal

The 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 a values mod 26: 1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25.
  • a = 1 reduces to a Caesar shift by b.
  • a = 25, b = 25 is Atbash.
  • Challenges over a 36- or 95-character alphabet change which a values are legal - the coprimality condition is against the alphabet size, not always 26.

Worked example

Affine with a=5, b=8

Input

AFFINE CIPHER

Result

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 workspace

Go deeper

Related tools