Hill cipher 2×2
With the key numbers 3, 3, 2 and 5, HELP encrypts to HIAT: each pair of letters is multiplied by the key matrix modulo 26. You also see the determinant, 9 here, and the inverse matrix needed to decrypt. Free in your browser.
- Free
- Runs in your browser
- No sign-up
- Your data stays on your device
Run — free
Worked example
- Text
- HELP
- A
- 3
- B
- 3
- C
- 2
- D
- 5
- Calculation mode
- Encrypt
- Result
- HIAT
- Det
- 9
- Det inv
- 3
- Inverse
- 15, 17, 20, 9
The Hill cipher is a classical polygraphic substitution invented by Lester S. Hill that encrypts blocks of letters with modular linear algebra instead of a single shift or keyword alphabet. In the two-by-two form, every pair of letters becomes a column vector multiplied by a four-entry key matrix modulo twenty-six, so the ciphertext of each digraph depends on both plaintext letters at once. Decryption multiplies by the modular inverse of that matrix, which exists only when the determinant is coprime with twenty-six. Students, CTF players, and puzzle authors use the 2×2 case because the arithmetic stays small while still demonstrating invertible matrices over Z/26Z. This capability accepts non-empty text, four integer key entries a, b, c, and d, and an optional encrypt or decrypt mode; it returns the transformed letter stream plus determinant, inverse matrix, and digraph metadata.
How the 2×2 Hill cipher works
Encryption treats each Latin letter as a number from zero through twenty-five and processes the stream two letters at a time. For a digraph with numeric values x1 and x2 and key matrix K equal to the rows a b on top and c d on the bottom, the ciphertext pair is y1 equals a times x1 plus b times x2 modulo twenty-six and y2 equals c times x1 plus d times x2 modulo twenty-six. The letters are written back as uppercase A through Z.
Digits, spaces, punctuation, emoji, and non-Latin scripts are stripped before pairing so the matrix always sees a pure alphabet stream; if the filtered letter count is odd on encrypt, a single padding X is appended so every block is a digraph. Decryption recovers plaintext by computing the modular matrix inverse of K and multiplying the same way, which requires that the determinant ad minus bc reduced modulo twenty-six be coprime with twenty-six. Optional mode accepts encrypt and encode for the forward map and decrypt and decode for the inverse.
Validation rules, invertible matrices, and common pitfalls
Text that contains no Latin letters after filtering also fails, because there is nothing to form digraphs. The decisive product rule is invertibility of the key matrix modulo twenty-six: the determinant det equals a times d minus b times c reduced into zero through twenty-five must satisfy gcd of det and twenty-six equal to one.
When that gcd is greater than one the map is not bijective on digraphs and decryption cannot be unique, so the capability reports a non-invertible key matrix with the computed determinant and gcd in the error message. Valid determinants are the units of Z/26Z—one, three, five, seven, nine, eleven, fifteen, seventeen, nineteen, twenty-one, twenty-three, and twenty-five—so singular or even-only structures such as a doubled identity often fail.
On decrypt, an odd letter count after filtering is rejected because ciphertext must arrive in complete digraphs; encrypt may pad with X but decrypt will not invent a missing letter. Do not treat the output as encryption for confidentiality: the key space of four small residues is tiny, known-plaintext attacks recover linear systems quickly, and the product page should never market Hill as a security control for passwords, tokens, or personal data.
Prefer this landing when the search intent is hill cipher, 2x2 hill cipher, or matrix cipher mod 26; affine answers monoalphabetic linear maps, Playfair answers digraph rectangles, and Base64 answers encoding, so they stay separate tools. When decrypting, use the same a, b, c, and d that produced the ciphertext; a wrong invertible matrix yields a different digraph substitution that will not match the original plaintext.
Classroom uses and practical limits
Call the free in-browser Hill cipher for homework checks, lecture slides, CTF practice, and one-off encrypt or decrypt runs without reimplementing modular matrix inverse in every language. A typical classroom workflow starts with the identity matrix to show that digraphs pass through unchanged when K is the identity, then switches to the textbook three-three-two-five key and walks students through multiplying HELP into HIAT by hand before comparing with the tool.
Teachers can deliberately submit a non-invertible matrix such as two zero zero two to demonstrate that gcd of the determinant with twenty-six blocks decryption, which is a core linear-algebra lesson over modular rings. 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 the 2×2 Hill cipher on its own landing so SEO intent stays sharp around matrix digraph substitution modulo twenty-six.
What you can do with it
Cryptanalysis homework and CTF warm-ups
Students encrypt short phrases with a known 2×2 key, decrypt classmates' digraph ciphertext, or verify hand-worked modular matrix multiplications without installing a CAS.
FAQ
How do I encrypt text with the 2×2 Hill cipher?
The response result field holds the uppercase ciphertext digraphs.
How do I decrypt Hill ciphertext?
Send the ciphertext as text, the same a,b,c,d used to encrypt, and mode decrypt (or decode). The result is the reconstructed uppercase letter stream when the key matches; odd letter counts after filtering are rejected.
What happens if the key matrix is not invertible mod 26?
Decryption requires gcd(det(K),26)=1; otherwise the digraph map is not bijective.
Is the Hill cipher 2×2 tool free?
The browser tool runs free on your device.
Is the Hill cipher secure encryption?
No. Hill is a classical polygraphic cipher for puzzles and teaching, not confidentiality. Never use it for passwords or sensitive data.
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/hill-2x2 \
-H "Authorization: Bearer $KIT_KEY" \
-H "Content-Type: application/json" \
-d '{"text":"HELP","a":3,"b":3,"c":2,"d":5}'const res = await fetch("https://api.kit.forhosting.com/enc/hill-2x2", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.KIT_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"text": "HELP",
"a": 3,
"b": 3,
"c": 2,
"d": 5
})
});
const { task_id } = await res.json();import os, requests
res = requests.post(
"https://api.kit.forhosting.com/enc/hill-2x2",
headers={"Authorization": f"Bearer {os.environ['KIT_KEY']}"},
json={
"text": "HELP",
"a": 3,
"b": 3,
"c": 2,
"d": 5
},
)
task_id = res.json()["task_id"]<?php
$res = file_get_contents("https://api.kit.forhosting.com/enc/hill-2x2", false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Authorization: Bearer " . getenv("KIT_KEY") . "\r\nContent-Type: application/json",
"content" => '{"text":"HELP","a":3,"b":3,"c":2,"d":5}',
],
]));
$task = json_decode($res, true);body := bytes.NewBufferString(`{"text":"HELP","a":3,"b":3,"c":2,"d":5}`)
req, _ := http.NewRequest("POST", "https://api.kit.forhosting.com/enc/hill-2x2", 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": "HELP",
"a": 3,
"b": 3,
"c": 2,
"d": 5
}Example response
{
"task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
"type": "enc.hill_2x2",
"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 the key matrix is not invertible modulo twenty-six the request fails with invalid_input and a clear non-invertible key matrix message.
How the 2×2 Hill map works and what the response contains
Send JSON with required string field text set to any non-empty message that still has at least one letter after filtering, required integers a, b, c, and d each in zero through twenty-five, and optional mode defaulting to encrypt; aliases input, value, s, message, plaintext, and ciphertext work for the body, while k11, m11, and key_a alias a, k12 style aliases cover b, c, and d. On success the response includes result with the uppercase transformed letters, mode normalized to encrypt or decrypt, the four key entries, det and det_inv for the determinant path, inverse as a flat four-number list of K inverse, key_matrix as the nested two-by-two array, letters_in showing the filtered and possibly padded stream that entered the matrix, digraph_count, padded boolean, length of the original text string, and method equal to hill_2x2 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, invertible matrices, 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, b, c, or d, non-integer keys, or values outside zero through twenty-five fail with invalid_input as well.
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 key_matrix, det, inverse, 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 linear algebra demos
Teachers show that only matrices with det coprime to 26 are invertible, contrast Hill digraphs with monoalphabetic affine maps, and pin a=3,b=3,c=2,d=5 as a textbook fixture.
Pipeline and CI fixtures
Scripts and continuous-integration tests pin deterministic Hill outputs and the non-invertible key matrix error so accidental determinant or inverse bugs fail fast.