我们在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,但没有成功。使用相同的测试数据,python版本返回的加密值不相同。
我们的python版本是als,如下:
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版本有什么问题