Recover a single-byte XOR key

A free medium coding practice problem from security. Solve it in JavaScript, TypeScript or Python and check your solution against fresh hidden tests — edge cases and random inputs — as often as you like.

Difficulty
Medium
Type
Function
Topic
Security
Languages
JavaScript, TypeScript or Python

Problem

data is a message (an array of byte values 0–255) encrypted by XOR-ing every byte with the same secret key byte. Find the key by trying all 256 keys 0 … 255 and scoring each decryption: for every decrypted byte b = data[i] XOR key add
- 3 if b is a lowercase letter a–z (97–122)
- 2 if b is a space (32)
- 1 if b is an uppercase letter A–Z (65–90)
- 0 if b is any other printable character (33–126)
- −5 otherwise (0–31 and 127–255)

Return the key with the HIGHEST total score; on a tie, the smallest key. An empty data returns 0. Up to 10 000 bytes.

Function signature

// JavaScript
function recoverXorKey(data)

// TypeScript
function recoverXorKey(data: any): any

// Python
def recover_xor_key(data):

Examples

  1. recoverXorKey([54,42,43,49,98,43,49,98,35,98,49,39,33,48,39,54]) → 66
  2. recoverXorKey([0,0,0]) → 97
  3. recoverXorKey([]) → 0

How checking works

Run your code against the examples above, then submit a check: it runs on the server against hidden tests built fresh each time, including edge cases and random inputs. Practice is untimed and never affects a verified score; when you are ready, take a graded coding challenge to earn a badge.

More practice problems

Next steps