We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Substitution Box

Substitution boxes, also known as s-boxes are a key component of many symmetric key algorithms, particularly block ciphers. The primary goal of an s-box, at least in this context, is to obscure the relationship between the key and the ciphertext. An attacker should not be able to derive information about the key from the ciphertext. For this lesson, the s-box examples are completely arbitrary.

Example

Here's a realistic S-box that maps a 6-bit input into a 4-bit output:

  • 011011 -> 1001
  • 011111 -> 0110

At the end of the day, an s-box is just a lookup table.

Assignment

Forget the above example. Use this simpler lookup table for the assignment:

Complete the sBox() function. It maps the last 4 bits of a byte down to the last 2 bits of a byte.

  • sBox(0b0000) -> 0b00
  • sBox(0b0001) -> 0b10
  • sBox(0b1111) -> 0b00
  • sBox(0b0110) -> 0b11 (e.g. 0b00000110 -> 0b00000011)

Each column represents the first two bits of input, the rows represent the second two bits. This is not the same as the 6-bit to 4-bit mapping table!

If an input value is outside the range of the table, return an error with the text invalid input.

Note on the byte Values

While we're working with entire byte values, just understand that we only care about the last (smallest in value) 4 and 2 bits for the input and output respectively. For example:

0b0110 -> 0b11 is the same as 0b00000110 -> 0b00000011)