PHP替代python加密代码

It's not my strong point the encryption, but I need to translate some python code to PHP. Maybe someone can help me.

The Python code:

import base64
import Crypto.Cipher.AES as AES
from Crypto.Util import Counter

counter = 5
key = bytes("my_secret_key_xx")
ctr=Counter.new(128, initial_value= counter)


ivBytes = bytearray(16)
ivBytes[3] = counter % 256
ivBytes[2] = (counter >> 8) % 256
ivBytes[1] = (counter >> 16) % 256
ivBytes[0] = (counter >> 24) % 256

cipher = AES.new(key, AES.MODE_CTR, IV = bytes(ivBytes), counter=ctr)
print base64.b64encode(ivBytes);
print base64.b64encode(cipher.encrypt(bytes("hola")))

More or less I understand it, is the basic CTR encryption, but with a custom starting counter. But I don't know how to set that custom counter in PHP.

$cipher = MCRYPT_RIJNDAEL_128;   
$key = "my_secret_key_xx";
$toEncrypt = "hola";
$counter = 5;
$b = array_reverse(unpack("C*", pack("L", $counter)));
$b = chr($b[0]).chr($b[1]).chr($b[2]).chr($b[3]).str_repeat("\0", 12);
$iv = $b;
$enc_data = mcrypt_encrypt($cipher, $key, $toEncrypt, "ctr", $iv);

echo ("b64Encryted-> ".base64_encode($enc_data))."
";
echo ("b64IV-> ".base64_encode($iv))."
";

Ok, I found the real problem, the Python code was confusing. The parameter IV in the

AES.new(key, AES.MODE_CTR, IV = bytes(ivBytes), counter=ctr)

does nothing, because the IV that AES with MODE_CTR uses on the encryption/decryption is the 16 byte (specified as 128 in the Counter.new) value that the counter returns every time is called. So, I think, that the IV parameter and it's calculation is there just to know what Counter returns where is called.

The PHP code:

    $cipher = MCRYPT_RIJNDAEL_128;
    $key = "my_secret_key_xx";
    $toEncrypt = "hola";
    $counter = 1235;
    //int to byte array
    $b = array_reverse(unpack("C*", pack("L", $counter)));
    //byte array to string
    $ctr_str = implode(array_map("chr", $b));
    // create 16 byte IV from counter
    $ctrVal = str_repeat("\x0", 12).$ctr_str;

    echo "Before
";
    echo "-----------------
";
   // echo "Counter: ".$c ." -- ".base64_encode($c)."
";
    echo "Key (base64): ".base64_encode($key)."
";
    echo "Secret (base64): ".base64_encode($toEncrypt)."
";
    echo ("IV (base64): ".base64_encode($ctrVal))."


";

    $enc_data = mcrypt_encrypt($cipher, $key, $toEncrypt, "ctr", $ctrVal);
    echo "Encryption
";
    echo "--------------
";
    echo ("Encrypted (base64):  ".base64_encode($enc_data))."


";

    echo "Decryption
";
    echo "-------------
";
    echo "Decrypted: ". mcrypt_decrypt($cipher, $key, $enc_data, "ctr", $ctrVal)."
";

Result:

    Before
    -----------------
    Key (base64): bXlfc2VjcmV0X2tleV94eA==
    Secret (base64): aG9sYQ==
    IV (base64): AAAAAAAAAAAAAAAAAAAE0w==


    Encryption
    --------------
    Encrypted (base64):  a22lbg==


    Decryption
    -------------
    Decrypted: hola