drio


I’m working through the Cryptopals challenges to learn more about cryptography. This post covers Set 1.

01: Hex to base64

The first thing to keep in mind is that we’re working with bytes. Always do your computations on bytes. Once you’re done, you can convert to hex or base64.

The hex package in Go helps convert from hex to bytes. Then you can use the encoding/base64 package to encode those bytes in base64. Easy.

02: Fixed XOR

Here we want to apply XOR between two equal-length byte slices. The inputs
come in hex, so convert them to bytes first. Then loop over both slices and
apply the ^ operator to each pair of bytes. When done, convert the result
back to hex. Easy.

03: Single-byte XOR cipher

Things get more interesting here. We’re given an encoded string that has been
XOR’d with a single character. The task is to find the key and decrypt it.

To do that, we try all printable ASCII characters as possible keys. For each
one, we create a repeated-key string of the same length as the ciphertext.
Then we XOR the ciphertext with that string.

To find the best result, we score the output by how closely it matches
English. For each byte, we add a value based on letter frequency in English.
The idea is that the right key gives the highest score.

04: Detect single-character XOR

Here we get a list of hex strings. One of them was XOR’d with a single
character. We apply the same method as challenge 3 to each string and return
the one that scores best.

05: Implement repeating-key XOR

Now we XOR the plaintext using a repeating key (“ICE”). The first byte is
XOR’d with ‘I’, the second with ‘C’, the third with ‘E’, then we repeat.
Use modulo arithmetic to wrap around the key.

06: Break repeating-key XOR

PART 1: Finding the keysize

The idea is that if you guess the correct keysize, ciphertext blocks
encrypted with the same key bytes will be statistically similar.

To find the keysize:

We normalize to avoid bias toward longer blocks, which naturally have higher
raw distances.

PART 2: Recovering the key

Now that we have the most likely keysize:

07: AES in ECB mode

Now we work with block ciphers. We’re given a base64-encoded ciphertext and a
key. We decode the text and decrypt it using AES-128 in ECB mode.

ECB mode encrypts each 16-byte block independently. The same input block
always gives the same output block.

Use the aes package in Go. Create a cipher
and decrypt the data block by block using the given 16-byte key.

08: Detect AES in ECB mode

We’re given many ciphertexts. One was encrypted with AES-128 in ECB mode. The
rest were not.

To find it:

ECB is deterministic: the same plaintext block always gives the same
ciphertext block. That makes it easy to spot.

Tags: programming cryptopals