* * Food for thought. * A folkloric supposed benefit of CTR mode is the ability to easily "seek forward" into the ciphertext; to access byte N of the ciphertext, all you need to be able to do is generate byte N of the keystream. Imagine if you'd relied on that advice to, say, encrypt a disk. */ require_once '../utils/random-bytes.php'; require_once '../03-block-and-stream-crypto/18-implement-ctr-the-stream-cipher-mode.php'; function editAES128CTR($ciphertext, $key, $nonce = "", $offset, $newtext) { $newLen = strlen($newtext); // really dirty - I could calculate block specific keys, but I don't really have to for this. $plaintext = encryptAES128CTR($ciphertext, $key, $nonce); $plainLen = strlen($plaintext); $newPlaintext = ''; if ($offset > 0) { $newPlaintext = substr($plaintext, 0, $offset); } $newPlaintext .= $newtext; if ($newLen + $offset < $plainLen) { $newPlaintext .= substr($plaintext, $newLen + $offset); } return encryptAES128CTR($newPlaintext, $key, $nonce); } // don't output if we're included into another script. if (!debug_backtrace()) { $key = getRandomBytes(16); $nonce = getRandomBytes(16); $ciphertext = encryptAES128CTR(decryptAES128ECB(base64_decode(file_get_contents('25-data.txt')), 'YELLOW SUBMARINE'), $key, $nonce); $editedCiphertext = editAES128CTR($ciphertext, $key, $nonce, 0, str_repeat("", strlen($ciphertext))); print "Recovered plaintext:\n"; print $ciphertext ^ $editedCiphertext . "\n\n"; }
function decryptedProfile($ciphertext, $key) { parse_str(decryptAES128ECB($ciphertext, $key), $profile); return $profile; }
{ $blocks = str_split($data, 16); foreach ($blocks as &$block) { $block = _decryptAES128ECB($block, $key); } $plaintext = implode($blocks); try { return removePKCS7Padding($plaintext); } catch (Exception $e) { if ($strictPadding) { throw $e; } return $plaintext; } } // don't output if we're included into another script. if (!debug_backtrace()) { $encrypted = base64_decode(file_get_contents('07-data.txt')); $key = 'YELLOW SUBMARINE'; $decryptedSane = removePKCS7Padding(_decryptAES128ECB($encrypted, $key)); $decrypted = decryptAES128ECB($encrypted, $key); print "Sanity check:\n"; $sanity = $decryptedSane === $decrypted; print $sanity ? "Success!\n\n" : "Failure :(\n\n"; print "Homebrew sanity check:\n"; $test = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; $sanity = decryptAES128ECB(encryptAES128ECB($test, $key), $key) === $test; print $sanity ? "Success!\n\n" : "Failure :(\n\n"; print "Decrypted data:\n"; print "{$decrypted}\n"; }