Affine Cipher

Encode and decode messages with the Affine substitution cipher.

How it is calculated

Each letter is turned into a number x (A = 0 … Z = 25). Encoding applies y = (a·x + b) mod 26. Decoding applies x = a⁻¹·(y − b) mod 26, where a⁻¹ is the modular inverse of a, the number for which a·a⁻¹ ≡ 1 (mod 26). The number is turned back into a letter.

The key a must share no factor with 26 (gcd(a, 26) = 1), otherwise the tool returns nothing, since decoding would be ambiguous. Upper and lower case are kept, and digits, spaces, punctuation and accented characters are copied through unchanged. Only the 26 letters A to Z are shifted. The mode field selects encode or decode.

Worked example

Encode Hello, World! with a = 5, b = 8. H is 7: 5 × 7 + 8 = 43, and 43 mod 26 = 17, which is R. E is 4: 5 × 4 + 8 = 28, and 28 mod 26 = 2, which is C. Continuing for every letter and keeping the case, comma, space and exclamation mark gives Rclla, Oaplx!. Decoding that text with the same keys returns Hello, World!.

Try this example →

Common mistakes

  • Choosing an even a or a multiple of 13 (such as 2, 4 or 13). Those share a factor with 26, so the tool gives no result; use 1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23 or 25.
  • Decoding with the wrong mode or different keys than were used to encode. You must set mode to decode and enter the same a and b.
  • Using a = 1 and expecting something stronger than a Caesar shift. With a = 1 the cipher is just a shift by b.
  • Expecting digits or accented letters to be encrypted. They pass through unchanged, which can reveal parts of the message.
  • Treating the cipher as secure. With only 12 valid values of a and 26 of b, there are just 312 key pairs, which are easy to try all.

About this calculator

This tool encrypts and decrypts text with the Affine cipher, a substitution cipher defined by E(x) = (a·x + b) mod 26, where x is a letter's numeric position (A=0…Z=25), a and b are the encryption keys, and the result maps back to a letter. Because it needs modular division to decrypt, key a must be coprime with 26 (share no common factor besides 1) — valid choices are 1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25.

It's a classic teaching example in introductory cryptography courses because it generalizes both the Caesar cipher (when a=1) and simple multiplicative ciphers, while showing why modular arithmetic and coprimality matter for invertibility. Enter your text and the two keys a and b to encode or decode a message.

Was this helpful?

You can pick up to 3 reactions.

Comments (0)

  • Be the first to comment.

Popular calculators

All Calculators