Question

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!

Was it helpful?

Solution

Block cipher modes are really simple, you can just implement them yourself if two implementations aren't compatible.

Here is a CTR implementation for your particular case:

function ctr_crypt($str, $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(MCRYPT_RIJNDAEL_128, $key, $ctrStr, MCRYPT_MODE_ECB);
}

The algorithm is very simple: You always append and increment the IV until you have a string that is longer (or of equal length) as the input string. Then you encrypt this string using ECB mode and XOR it with the input string.

The incrementation is the complicated part here, because we are dealing with a number in binary. Little Endian means we increment from left to right (j = 0, j < 16, j++). Big Endian would mean that we increment from right to left (j = 15, j >= 0, j--).

Try it out:

$encrypted = base64_decode('MlNFlnXE1sqIsmKZRtjChBvUMgiJlXgdjHVxQJ6JK24Id4uaN9NK/nBtY+cgrMJR/PRJRCmIUx0boQO5XqJYZ8VJ0w==');
$key = base64_decode('HB+dD1Irj2rXQ/nO+IuqSiK9xVE3PD9cZGIGzrMtwtA=');
$iv = base64_decode('2gxxKYU/G4lj7174e5wj+g==');

var_dump(ctr_crypt($encrypted, $key, $iv));
// string(67) "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do..."

Note: ctr_crypt works both as an encryption and as a decryption function.

OTHER TIPS

Looks like PHP's mcrypt uses other CTR mode (big endian instead of little endian). Key schedule and IV are ok (as you can see on decrypting the first block), but something goes wrong in IV incrementing function.

See the following PHP code, which solves your problem by manually incrementing IV and encrypting gamma in ECB mode:

<?php
$encrypted = base64_decode('MlNFlnXE1sqIsmKZRtjChBvUMgiJlXgdjHVxQJ6JK24Id4uaN9NK/nBtY+cgrMJR/PRJRCmIUx0boQO5XqJYZ8VJ0w==');
$key = base64_decode('HB+dD1Irj2rXQ/nO+IuqSiK9xVE3PD9cZGIGzrMtwtA=');
$iv = base64_decode('2gxxKYU/G4lj7174e5wj+g==');

$ivarr = array_values(unpack('C*', $iv));
$ivdata = array_merge($ivarr);
$blocklen = count($ivarr);

for ($i = 1; $i < strlen($encrypted)/strlen($iv); $i++)
{
    // incrementing IV
    $ivarr[0] += 1;
    if ($ivarr[0] == 256)
    $ivarr[0] = 0;

    $j = 0;
    while ($ivarr[$j] == 0)
    {   
    $j++;
    if ($j == $blocklen)
        break;
    $ivarr[$j]++;
    }
    // appending to array
    var_dump($ivarr);
    $ivdata = array_merge($ivdata, $ivarr);
}

// now ivdata contains the full CTR gamma. Encrypting it.

$cryptor = mcrypt_module_open('rijndael-128', '', 'ecb', '');
$res = mcrypt_generic_init($cryptor, $key, "");

$ivdatastr = implode(array_map("chr", $ivdata));
$ivdecr = mcrypt_generic($cryptor, $ivdatastr);

$ivdecr = array_values(unpack('C*', $ivdecr));
$decrypted = array_values(unpack('C*', $encrypted));
$i = 0;

for ($i = 0; $i < count($decrypted); $i++)
{
    $decrypted[$i] = $decrypted[$i] ^ $ivdecr[$i % count($ivdecr)];
}    

$string = implode(array_map("chr", $decrypted));

var_dump($string);

mcrypt_generic_deinit($cryptor);
mcrypt_module_close($cryptor);
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top