A toy cipher in CBC mode

CBC mode XORs each plain block with the previous cipher block before encrypting it, starting from a random IV. Here each block is one byte and a toy cipher stands in for AES.

What to build

Encrypt a line of text in CBC mode, or decrypt a list of bytes back to text.

Requirements

  • The toy block cipher is E(x) = ((x XOR key) × 5 + 3) mod 256, and its inverse is D(y) = (((y − 3) × 205) mod 256) XOR key. (205 works because 5 × 205 = 1025, which is 1 more than 4 × 256.)
  • Encrypt: c₁ = E(p₁ XOR IV), and each later cᵢ = E(pᵢ XOR cᵢ₋₁), where pᵢ are the character codes. Print the bytes separated by spaces.
  • Decrypt: pᵢ = D(cᵢ) XOR cᵢ₋₁, with c₀ = IV. Print the text.
  • In D, keep (y − 3) × 205 non-negative before taking mod 256 (add 256 when y < 3).

Input

Line 1: encrypt or decrypt. Line 2: the key (0 to 255). Line 3: the IV (0 to 255). Line 4: the text to encrypt, or the bytes to decrypt separated by spaces.

Output

One line.

Constraints

1 to 100 characters or bytes. Text characters have codes 32 to 126.

Example

Input:

encrypt
77
19
AAAABBBBAAAA

Output:

158 221 24 103 11 23 123 71 122 81 212 59

Why it works

Each step of encryption is undone by the matching step of decryption in reverse order: D undoes E, and XOR with the previous cipher block undoes the XOR made before encrypting, which is why CBC needs the previous cipher block (or the IV) to decrypt.

Examples

Example 1 · Input
encrypt
77
19
AAAABBBBAAAA
Expected output
158 221 24 103 11 23 123 71 122 81 212 59
Example 2 · Input
decrypt
77
19
158 221 24 103 11 23 123 71 122 81 212 59
Expected output
AAAABBBBAAAA

Hints

Hint 1

Write E and D as two small functions first and check that D(E(x)) is x for every x from 0 to 255.

Hint 2

Keep a variable prev that starts as the IV and becomes each cipher byte in turn.

Solution

Show one correct solution (try it yourself first)
const mode = prompt().trim();
const key = Number(prompt());
const iv = Number(prompt());
const data = prompt();
const E = (x) => ((x ^ key) * 5 + 3) % 256;
const D = (y) => ((((y - 3 + 256) % 256) * 205) % 256) ^ key;
let prev = iv;
if (mode === "encrypt") {
  const out = [];
  for (const ch of data) {
    prev = E(ch.charCodeAt(0) ^ prev);
    out.push(prev);
  }
  console.log(out.join(" "));
} else {
  let text = "";
  for (const c of data.trim().split(/\s+/).map(Number)) {
    text += String.fromCharCode(D(c) ^ prev);
    prev = c;
  }
  console.log(text);
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Symmetric encryption and AES →