3

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!

2

2 Answers 2

3
+100

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.

9
  • + Nice ... but don't you think you should advice against ECB ?
    – Baba
    May 18, 2013 at 16:09
  • @Baba This implements a CTR encryption mode. ECB is only used in the implementation of it ;)
    – NikiC
    May 18, 2013 at 17:14
  • i was not referring to the to the CTR implementation but ECB in general ... He might sill be safe if key & IV is not reused but iOS 5.x's CommonCrypto still has better alternatives ... but i guess the question was all about Decrypting AES CTR Little Endian ... nice one anyway :)
    – Baba
    May 18, 2013 at 21:16
  • Well, look at that. NikiC, your counter incrementing is "right", and your function works with shorter string+IV combinations that don't trigger the byte overflow. But with those that do, the results end up not being compatible with CommonCrypto. It appears CommonCrypto doesn't handle overflow properly, and only ever increments $iv[0], since it worked when I modified your function to do it that way. Weird. Anyway, you still deserve the bounty NikiC. Thanks again!
    – curtisdf
    May 21, 2013 at 5:46
  • @curtisdf That sounds very odd. If they really only increment the first character, then the used xor key would repeat after 16*256 characters (thus any longer cipher would be trivially breakable using frequency analysis). Could you try encrypting a long string (like 100000 characters) of only As and dump the resulting cipher (in hex/base64) somewhere?
    – NikiC
    May 21, 2013 at 15:37
0

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);
?>
10
  • Any pointers on how to use Little Endian? Is there a PHP alternative to MCrypt that would do this?
    – curtisdf
    May 10, 2013 at 19:44
  • It would be easier to change the iOS compatible code, but I don't know if you can change that. May 11, 2013 at 0:21
  • At least you can manually increment IV for each block and use it. However, this would be slow. Easier would be to switch to CBC mode, or change endiannes on iOS side, as owlstead suggested. May 11, 2013 at 7:51
  • Unfortunately, changing the encryption on the iOS side is not an option. But speed isn't so much a problem, since my PHP code will be doing it as a background process. @NickolayOlshevsky -- Any pointers for how to implement IV incrementing in the manner that's needed? I don't really understand endianness and CTR block incrementing.
    – curtisdf
    May 16, 2013 at 17:24
  • See the updated answer. I don't know why I did it (coding byte-operations in PHP is a total pain), but it works. May 17, 2013 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.