I have python code
from Crypto.Cipher import AES
def pad(data):
block_size = 16
bytes_to_add = block_size - ((len(data) % block_size) or block_size)
return data + (b'\0' * bytes_to_add)
cipher = AES.new(b"4452038393672345", AES.MODE_ECB)
body = pad("asa masa".encode('utf-8'))
content = base64.b64encode(cipher.encrypt(body)).decode('ascii')
I see result "sEP5RCWmdQdPYo/eeWVIwg=="
I want to port python code to php using openssl
function pad($data) {
$block_size = 16;
$bytes_to_add = $block_size - ((strlen($data) % $block_size) ?: $block_size);
return $data . str_repeat("\0", $bytes_to_add);
}
$cipher = "AES-128-ECB";
$options = OPENSSL_RAW_DATA;
$plainText = pad("asa masa");
$key = '4452038393672345';
$encryptedText = openssl_encrypt($plainText, $cipher, $key, $options);
$encodedText = base64_encode($encryptedText);
I see result from openssl "c0VQNVJDV21kUWRQWW8vZWVXVkl3dWZPTjExZ21iUG1VQUI0c0EwaktVaz0="
Another code in php
$rawData = openssl_encrypt(pad("asa masa"), 'AES-128-ECB', '4452038393672345');
return "sEP5RCWmdQdPYo/eeWVIwufON11gmbPmUAB4sA0jKUk="
If anyone is interested, do it this way and everything is fine
If anyone is interested, do it this way and everything is fine
$encrypted = openssl_encrypt(pad("asa masa"), 'AES-128-ECB', '4452038393672345',OPENSSL_RAW_DATA | OPENSSL_DONT_ZERO_PAD_KEY | OPENSSL_ZERO_PADDING);
$encrypted=base64_encode($encrypted);
Result is "sEP5RCWmdQdPYo/eeWVIwg=="
Thanks
if we refer to https://www.php.net/manual/en/function.openssl-encrypt.php
OPENSSL_RAW_DATA = 1 (binary:
01) OPENSSL_ZERO_PADDING = 2 (binary:10)so:
and the pattern repeats since we're only looking for last 2 bits
OPENSSL_RAW_DATA | OPENSSL_DONT_ZERO_PAD_KEY | OPENSSL_ZERO_PADDING = 1 | 4 | 2 = 7 so we get
openssl_encrypt($plainText, $cipher, $key, 7)by default
openssl_encryptusesPKCS#7padding which causes "double padding" (your zero pad + PKCS) that's why in you should use OPENSSL_ZERO_PADDING in your case (it's recommended to use defaultopenssl_encryptpadding)if you visit https://www.base64decode.org/ you can see that
c0VQNVJDV21kUWRQWW8vZWVXVkl3dWZPTjExZ21iUG1VQUI0c0EwaktVaz0=is base64 encodedsEP5RCWmdQdPYo/eeWVIwufON11gmbPmUAB4sA0jKUk=andsEP5RCWmdQdPYo/eeWVIwufON11gmbPmUAB4sA0jKUk=is justsEP5RCWmdQdPYo/eeWVIwg==with some additional stuff caused by double padding