PHP 替代 python 加密代码

PHP substitute of python encryption code

加密不是我的强项,但我需要将一些 python 代码翻译成 PHP。也许有人可以帮助我。

Python代码:

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")))

我大概理解了,就是基本的CTR加密,但是有一个自定义的起始计数器。但我不知道如何在 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("[=13=]", 12);
$iv = $b;
$enc_data = mcrypt_encrypt($cipher, $key, $toEncrypt, "ctr", $iv);

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

好的,我找到了真正的问题,Python 代码令人困惑。

中的参数IV
AES.new(key, AES.MODE_CTR, IV = bytes(ivBytes), counter=ctr)

什么都不做,因为带有 MODE_CTR 的 AES 在 encryption/decryption 上使用的 IV 是计数器 [=26] 的 16 字节(在 Counter.new 中指定为 128)值=] 每次都被调用。所以,我认为,IV 参数及其计算只是为了知道调用了什么 Counter returns。

PHP代码:

    $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\n";
    echo "-----------------\n";
   // echo "Counter: ".$c ." -- ".base64_encode($c)."\n";
    echo "Key (base64): ".base64_encode($key)."\n";
    echo "Secret (base64): ".base64_encode($toEncrypt)."\n";
    echo ("IV (base64): ".base64_encode($ctrVal))."\n\n\n";

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

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

结果:

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


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


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