Hashing, encoding and basic security · 9 / 15 Exercise Medium

Toy XOR cipher

Objective

Applying XOR with a repeated key is a very weak “cipher”, but it illustrates an important idea: XOR is its own inverse, so the same operation encrypts and decrypts. Do not use this to protect real data.

Instructions

  • The first line has the number n of commands; each one is enc key text or dec key hex (one word per field, no spaces).
  • To encrypt, XOR each byte of the text (UTF-8) with the key byte at position i % len(key) (the key repeats) and show the result in hexadecimal. To decrypt, do the opposite. If the hexadecimal is not valid, show Error: invalid hexadecimal.
Input
2
enc k hola
dec k 03080d0a
Output
0304070a
hcfa

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise