Affine cipher
Encrypt or decrypt with the affine cipher, which multiplies each letter's position by a and adds b: with a set to 5 and b to 8, AFFINE CIPHER becomes IHHWVC SWFRCP. The inverse of a, here 21, is shown too. Free in your browser.
- Free
- Runs in your browser
- No sign-up
- Your data stays on your device
Run — free
Worked example
- Text
- AFFINE CIPHER
- A
- 5
- B
- 8
- Calculation mode
- Encrypt
- Result
- IHHWVC SWFRCP
- A inv
- 21
- Length
- 13
- Letters transformed
- 12
The affine cipher is a classical monoalphabetic substitution that maps each letter position x through the linear formula E(x)=(a·x+b) mod 26, where a is a multiplier coprime with twenty-six and b is an additive shift. Decryption multiplies by the modular inverse of a so every valid key pair is fully reversible. Unlike ROT13 or Atbash, both keys are free parameters within the legal set, which makes affine a standard teaching step between fixed-shift Caesar and full keyword monoalphabetic ciphers. People use it for cryptanalysis homework, CTF warm-ups, puzzle books, and classroom demos of modular arithmetic. This capability accepts non-empty text, integer keys a and b, and an optional encrypt or decrypt mode; it returns the transformed string with the inverse of a and a letter count.
Validation rules, coprime keys, and common pitfalls
The decisive product rule is that a must be coprime with twenty-six: gcd(a,26) must equal one so a modular inverse exists. Valid multipliers are one, three, five, seven, nine, eleven, fifteen, seventeen, nineteen, twenty-one, twenty-three, and twenty-five; even values and multiples of thirteen share a factor with twenty-six and are rejected with a clear message that a is not coprime.
Do not treat the output as encryption for confidentiality: the key space is tiny, frequency analysis still works, and the product page should never market affine as a security control for passwords, tokens, or personal data. Prefer this landing when the search intent is affine cipher, affine encrypt decrypt, or modular monoalphabetic cipher; Atbash and ROT13 answer fixed-map intents, rail fence answers transposition, and Base64 answers encoding, so they stay separate tools.
When decrypting, use the same a and b that produced the ciphertext; a wrong pair yields a different substitution that will not match the original plaintext.
Using it in class, and where it stops
Call the free in-browser affine cipher for homework checks, lecture slides, CTF practice, and one-off encrypt or decrypt runs without writing modular inverse code in every language. A typical classroom workflow shows that Caesar is the special case a equals one, then varies a among the coprime set and demonstrates that even multipliers break invertibility. Support playbooks can reverse lightly obfuscated notes that staff wrote with known classroom keys.
Puzzle sites can precompute answers for display and reveal them on demand with mode decrypt. Pair with frequency-analysis or other classical tools only when a later teaching step needs a different cipher family—keep affine on its own landing so SEO intent stays sharp around keyed modular substitution.
What you can do with it
Cryptanalysis homework and CTF warm-ups
Students encrypt short phrases with known a and b, then decrypt classmates' ciphertexts or recover keys under constraints without installing a CAS.
FAQ
How do I decrypt affine ciphertext?
Send the ciphertext as text, the same a and b used to encrypt, and mode decrypt (or decode). The result is the reconstructed plaintext when the keys match.
What happens if a is not coprime with 26?
The affine map is only bijective when gcd(a,26)=1; even multipliers and multiples of 13 are rejected.
Is the affine cipher tool free?
The browser tool runs free on your device.
Is the affine cipher secure encryption?
No. Affine is a classical monoalphabetic cipher for puzzles and teaching, not confidentiality. Never use it for passwords or sensitive data.
What happens to spaces, digits and capital letters?
Only Latin letters change. Digits, spaces, punctuation, emoji and other scripts pass through untouched, and each letter keeps its case, so AFFINE CIPHER keeps its space and capitals while the letters themselves are substituted.
Related tools
For developers — API access
Everything on this page is available programmatically. This section is for teams who want to wire it into their own systems; everyone else can just use the tool above.
API endpoint
Prefer to automate it? One authenticated POST creates the task; the result comes back by webhook or a signed link. The same capability also runs here on the web, by email and from Telegram — and soon from our app too.
Call it from your stack
curl -X POST https://api.kit.forhosting.com/enc/affine \
-H "Authorization: Bearer $KIT_KEY" \
-H "Content-Type: application/json" \
-d '{"text":"AFFINE CIPHER","a":5,"b":8}'const res = await fetch("https://api.kit.forhosting.com/enc/affine", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.KIT_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"text": "AFFINE CIPHER",
"a": 5,
"b": 8
})
});
const { task_id } = await res.json();import os, requests
res = requests.post(
"https://api.kit.forhosting.com/enc/affine",
headers={"Authorization": f"Bearer {os.environ['KIT_KEY']}"},
json={
"text": "AFFINE CIPHER",
"a": 5,
"b": 8
},
)
task_id = res.json()["task_id"]<?php
$res = file_get_contents("https://api.kit.forhosting.com/enc/affine", false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Authorization: Bearer " . getenv("KIT_KEY") . "\r\nContent-Type: application/json",
"content" => '{"text":"AFFINE CIPHER","a":5,"b":8}',
],
]));
$task = json_decode($res, true);body := bytes.NewBufferString(`{"text":"AFFINE CIPHER","a":5,"b":8}`)
req, _ := http.NewRequest("POST", "https://api.kit.forhosting.com/enc/affine", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("KIT_KEY"))
req.Header.Set("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)Example request
{
"text": "AFFINE CIPHER",
"a": 5,
"b": 8
}Example response
{
"task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
"type": "enc.affine",
"status": "queued",
"_links": {
"result": "/tasks/tsk_…/result"
}
}The API is asynchronous: the call returns a task_id immediately and the result arrives by webhook. Polling is capped at 1 req/s per task.
Pricing
Published price — no tokens, no invented credits. A failed task is never charged.
Errors
| HTTP | Code | Meaning |
|---|---|---|
401 | unauthorized | Missing or invalid API key. |
402 | insufficient_balance | Your balance doesn't cover the task price. |
404 | unknown_type | That task type doesn't exist. |
429 | rate_limited | Too many requests. Use the webhook instead of polling. |
Technical notes
When a shares a factor with twenty-six the request fails with invalid_input because the map would not be bijective.
How the affine map works and what the response contains
Encryption treats each Latin letter as a number from zero through twenty-five, multiplies by key a, adds key b, and reduces modulo twenty-six before writing the letter back with the original case. Uppercase A through Z and lowercase a through z use the same offsets so mixed-case phrases keep their shape while only letter identities change. Digits, spaces, punctuation, emoji, and non-Latin scripts pass through unchanged so messages keep spacing and symbols. Optional mode defaults to encrypt; encrypt and encode both run the forward map, while decrypt and decode reverse it. Decryption recovers plaintext by computing a modular inverse a_inv such that a·a_inv ≡ 1 mod 26, then evaluating D(y)=a_inv·(y−b) mod 26 for every letter. Send JSON with required string field text set to any non-empty message, required integer a in one through twenty-five that is coprime with twenty-six, and required integer b in zero through twenty-five; aliases input, value, s, and message work for the body, multiplier, key_a, and alpha alias a, while shift, key_b, and beta alias b. On success the response includes result with the transformed text, mode normalized to encrypt or decrypt, a and b echoing the keys, a_inv with the inverse used for decryption, length equal to the input character count, letters_transformed counting how many A–Z or a–z units actually moved, and method equal to affine so clients can branch without sniffing shapes. Identical inputs always produce identical JSON because the path is pure modular arithmetic with no network, no random seed, and no wall clock.
Validation rules, coprime keys, and common pitfalls
Missing text, non-string text, or an empty string all raise invalid_input and are not charged on the prepaid API after the engine rejects the request. Missing a or b, non-integer keys, a outside one through twenty-five, or b outside zero through twenty-five also fail with invalid_input. Whitespace, digits, and punctuation are not stripped: only Latin letters participate in the substitution, so punctuation-heavy strings still return a full result with a lower letters_transformed count.
API usage, pricing, classroom workflows, and practical limits
Use the prepaid KIT API when a backend, serverless function, tutoring platform, or SDK needs a stable contract under balance at $0.002 per successful item; validation failures never consume balance after rejection. Authors shipping SDKs can map the result field straight into a copy button while a, b, a_inv, and method make OpenAPI examples self-explanatory. Keep payloads to ordinary text sizes appropriate for a Worker isolate item call; this tool is for messages and snippets, not multi-megabyte binary blobs.
Integration use cases
Classroom modular arithmetic demos
Teachers show that only coprime multipliers are invertible, contrast affine with fixed Atbash or ROT13, and pin a equals five b equals eight as a textbook fixture.
Pipeline and CI fixtures
Scripts and continuous-integration tests pin deterministic affine outputs and the non-coprime a error so accidental inverse or gcd bugs fail fast.
Technical questions
How do I encrypt text with the affine cipher?
Send JSON with non-empty text, integer a coprime with 26 (for example 5), integer b in 0–25 (for example 8), and optional mode encrypt (the default). The response result field holds the ciphertext.