title: Decrypting AES CTR Little Endian with PHP
body: <p>I'm having trouble using PHP to decrypt strings that were encrypted with iOS 5.x's CommonCrypto libraries.  Here are the parameters:</p>
  
  <pre><code>Algorithm: AES-128
  Mode: CTR
  Mode options: CTR Little-Endian
  Padding: None
  </code></pre>
  
  <p>Here's a sample of my best attempt at it:</p>
  
  <pre><code>&lt;?php
  $encrypted = base64_decode('MlNFlnXE1sqIsmKZRtjChBvUMgiJlXgdjHVxQJ6JK24Id4uaN9NK/nBtY+cgrMJR/PRJRCmIUx0boQO5XqJYZ8VJ0w==');
  $key = base64_decode('HB+dD1Irj2rXQ/nO+IuqSiK9xVE3PD9cZGIGzrMtwtA=');
  $iv = base64_decode('2gxxKYU/G4lj7174e5wj+g==');
  
  $cryptor = mcrypt_module_open('rijndael-128', '', 'ctr', '');
  mcrypt_generic_init($cryptor, $key, $iv);
  echo mdecrypt_generic($cryptor, $encrypted);
  
  mcrypt_generic_deinit($cryptor);
  mcrypt_module_close($cryptor);
  </code></pre>
  
  <p>The output looks like this:</p>
  
  <pre><code>Lorem ipsum dolo?N??]ѕȢ?+?
                                               ????x??k????}??'???Ŧ??;t
  </code></pre>
  
  <p>But it should be "<strong>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do...</strong>" (trailing ellipsis included.)</p>
  
  <p>The block size is 16, and it's getting the first 16 characters right.  This seems to point to a mismatch in the AES CTR counter-incrementing process between Mcrypt and CommonCrypto.  Everybody I've heard from so far has suggested it's an issue of Big Endian vs. Little Endian.  </p>
  
  <p>I've spent days trying to figure out all this endianness and counter-incrementing stuff on my own, but it's still voodoo to me.  :-(  I just need some PHP code that properly decrypts my string.  I don't care how fast the algorithm works.  I'm open to ditching Mcrypt in favor of a PHP-native solution or some other PHP extension, as long as it's a common one.  However, changing things on the iOS side is <em>not</em> an option.</p>
  
  <p>Please help!</p>