Skip to content

Instantly share code, notes, and snippets.

@jaytaph
Created October 21, 2013 20:10
Show Gist options
  • Save jaytaph/7090112 to your computer and use it in GitHub Desktop.
Save jaytaph/7090112 to your computer and use it in GitHub Desktop.
/**
* Taken from Nikita Popov's answer on stack overflow: http://stackoverflow.com/questions/16489509/decrypting-aes-ctr-little-endian-with-php
*/
static public function ctr_crypt($str, $cipher = MCRYPT_RIJNDAEL_256, $key, $iv) {
$numOfBlocks = ceil(strlen($str) / 16);
$ctrStr = '';
for ($i = 0; $i < $numOfBlocks; ++$i) {
$ctrStr .= $iv;
// increment IV
for ($j = 0; $j < 16; ++$j) {
$n = ord($iv[$j]);
if (++$n == 0x100) {
// overflow, set this one to 0, increment next
$iv[$j] = "\0";
} else {
// no overflow, just write incremented number back and abort
$iv[$j] = chr($n);
break;
}
}
}
return $str ^ mcrypt_encrypt($cipher, $key, $ctrStr, MCRYPT_MODE_ECB);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment