0

we used the following function in PHP to encrypt some data:

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;
}

now we try to translate this to python but without success. with same testdata the python Version returns not the same encryption values.

Our python version is als follows:

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)

maybe anybody can tell whats wrong in our python version

Jack
  • 59
  • 7
  • There is a [openssl](https://pyopenssl.org/en/stable/api.html) library for Python. I noticed you're using the same in PHP? – Torxed Oct 24 '18 at 12:29
  • Try this ['Working example from GitHub'](https://stackoverflow.com/a/52646988/7414759), replace `AES.MODE_CBC` with `AES.MODE_CTR`. – stovfl Oct 24 '18 at 19:16
  • OK Found the error myself. instead of tc_bin = struct.pack('>I', data) i have to write: tc_bin = struct.pack('>Q', data) – Jack Oct 25 '18 at 05:43

0 Answers0