从php到python移植aes加密函数

2024-04-20 11:07:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我们在PHP中使用了以下函数来加密一些数据:

function aes_encrypt_turnover($reg_id,$receipt_nr,$data,$key_base64) {
    $method = 'AES-256-CTR';
    $library = 'OpenSSL';
    $tc_bin = pack("J",$data);
    $key_bin = base64_decode($key_base64);
    $iv_bin = substr(hash('sha256', $reg_id . $receipt_nr, true), 0, 16);
    $tc_encrypted_base64 = openssl_encrypt($tc_bin, $method, $key_bin, false, $iv_bin);
    return $tc_encrypted_base64;
}

现在我们尝试将其转换为python,但没有成功。对于相同的testdata,python版本返回不同的加密值

我们的python版本如下:

import base64
import struct
import hashlib

from Crypto.Cipher import AES
from Crypto.Util import Counter
from Crypto.Util.number import bytes_to_long

data = 12345
reg_id = "DEMO_DATA"
receipt_nr = 843234
key_base64 = 'RCsRmHn5tkLQrRpiZq2ucwPpwvHJLiMgLvwrwEImddI='

tc_bin =  struct.pack('>I', data)
key_bin = base64.b64decode(key_base64)

hash_string = str(reg_id) + str(receipt_nr)
iv_bin = hashlib.sha256(hash_string.encode()).digest()[:16]

counter = Counter.new(128, initial_value = bytes_to_long(iv_bin))

cipher = AES.new(key_bin, AES.MODE_CTR, counter=counter)
encrypted = cipher.encrypt(tc_bin)

encrypted_b64 = base64.b64encode(encrypted)

也许任何人都能看出我们的python版本有什么问题


Tags: keyimportiddatabinhashregnr