I'm having trouble using PHP to decrypt strings that were encrypted with iOS 5.x's CommonCrypto libraries. Here are the parameters:
Algorithm: AES-128
Mode: CTR
Mode options: CTR Little-Endian
Padding: None
Here's a sample of my best attempt at it:
<?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);
The output looks like this:
Lorem ipsum dolo?N??]ѕȢ?+?
????x??k????}??'???Ŧ??;t
But it should be "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do..." (trailing ellipsis included.)
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.
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 not an option.
Please help!