---
title: "Affine"
description: "E(x) = (a·x + b) mod 26. The multiplier must be coprime with 26, which leaves twelve of them and 312 keys."
canonical_url: "https://ciphers.agntn.dev/ciphers/affine"
---
# Affine

> E(x) = (a·x + b) mod 26. The multiplier must be coprime with 26, which leaves twelve of them and 312 keys.

<cipher-facts name="affine">



</cipher-facts>

A letter is its index x, 0 to 25. Encoding is `(a·x + b) mod 26`, decoding multiplies by the inverse of `a`. That inverse only exists when `gcd(a, 26) = 1`, so `a` is one of 1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23 or 25. Anything else is an `InvalidOptionError` before the first letter, because a cipher that maps two letters onto one can't be decoded and shouldn't pretend. `b` is a shift 0 to 25. Defaults are `a = 5`, `b = 8`.

```ts
const affine = create("affine");
affine.encode("AFFINE CIPHER", { a: 5, b: 8 }).text; // "IHHWVC SWFRCP"
affine.decode("IHHWVC SWFRCP", { a: 5, b: 8 }).text; // "AFFINE CIPHER"
affine.encode("X", { a: 13, b: 0 }); // throws, gcd(13, 26) = 13
```

`a = 1` is a [Caesar](https://ciphers.agntn.dev/ciphers/caesar) with shift `b`. `a = 25, b = 25` is [Atbash](https://ciphers.agntn.dev/ciphers/atbash). Twelve multipliers times 26 shifts is 312 keys - small enough to try every one.


## Sitemap

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