Cryptopals: Set 1 – challenge 7

Next up with Cryptopals is a challenge to decrypt AES in ECB mode. This is relatively easy in PHP!

It’s time to keep moving on with Cryptopals. Our next challenge is somewhat more fairly straight-forward than the last one: decrypt a ciphertext using AES.

The Base64-encoded content in this file has been encrypted via AES-128 in ECB mode under the key
(case-sensitive, without the quotes; exactly 16 characters; I like “YELLOW SUBMARINE” because it’s exactly 16 bytes long, and now you do too).

Decrypt it. You know the key, after all.


ECB mode is not the most secure way to use AES, but it does help illustrate the proper way to use the cipher in code. ECB always encrypts identical plaintext strings to identical ciphertext strings, meaning an attacker can easily guess which parts of a message are the same. In practice, you want to use more secure cipher modes … but ECB is still an option.

PHP bundles OpenSSL and exposes several functions for working with it: we’re going to focus on openssl_encrypt() and openssl_decrypt().

Assuming we’ve downloaded the referenced file and stored it as encrypted.txt, our entire routine is fairly straight-forward:

$ciphertext = file_get_contents('encrypted.txt');

$output = openssl_decrypt(
  $ciphertext,        // data
  'aes-128-ecb',      // algorithm

if ($output === false) {
  print openssl_error_string();

print $output;

I should point out that openssl_decrypt() will return either a string of decrypted bytes or false if there’s an error. We want to check for a false return explicitly. If there is an error, we can print that error message directly for further diagnostics.

Running this code successfully decrypts the contents of the message to the lyrics of Play That Funky Music by Vanilla Ice.