XOR with a key byte

XOR with the same key twice gives back what you started with, so one key both encrypts and decrypts: the idea behind symmetric encryption.

What to build

Encrypt a line of text by XOR-ing every character code with a key, print the bytes, then decrypt them again.

Requirements

  • Line 1 is the key, a whole number from 0 to 255.
  • Print the encrypted bytes as decimal numbers separated by spaces.
  • Then print decrypted: followed by the text you get by XOR-ing the bytes with the key again.

Input

Line 1: the key. Line 2: the text (character codes 32 to 126).

Output

Two lines.

Constraints

The text has 1 to 100 characters.

Example

Input:

90
Hi Rahim

Output:

18 51 122 8 59 50 51 55
decrypted: Hi Rahim

Why it works

XOR is its own inverse: (x ^ k) ^ k = x for every bit, so applying the same key a second time undoes the first.

Examples

Example 1 · Input
90
Hi Rahim
Expected output
18 51 122 8 59 50 51 55
decrypted: Hi Rahim
Example 2 · Input
0
abc
Expected output
97 98 99
decrypted: abc

Hints

Hint 1

text.charCodeAt(i) ^ key gives one encrypted byte.

Hint 2

String.fromCharCode(byte ^ key) turns it back into a character.

Solution

Show one correct solution (try it yourself first)
const key = Number(prompt());
const text = prompt();
const bytes = [];
for (let k = 0; k < text.length; k++) bytes.push(text.charCodeAt(k) ^ key);
console.log(bytes.join(" "));
console.log("decrypted: " + bytes.map((b) => String.fromCharCode(b ^ key)).join(""));

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

Lesson: Symmetric encryption and AES →