PHP替代python加密代码

时间:2015-09-14 20:29:06

标签: php python encryption aes

加密不是我的强项,但我需要将一些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("\0", 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";

1 个答案:

答案 0 :(得分:0)

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

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

不执行任何操作,因为带有MODE_CTR的AES在加密/解密时使用的IV是计数器每次调用时返回的16字节(在Counter.new中指定为128)值。因此,我认为,IV参数及其计算只是为了知道Counter返回的位置。

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