我有Python代码
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')
我看到结果“sEP5RCWmdQdPYo/eeWVIwg==”
我想使用 openssl 将 python 代码移植到 php
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);
我看到 openssl "c0VQNVJDV21kUWRQWW8vZWVXVkl3dWZPTjExZ21iUG1VQUI0c0EwaktVaz0="
的结果php 中的另一段代码
$rawData = openssl_encrypt(pad("asa masa"), 'AES-128-ECB', '4452038393672345');
返回“sEP5RCWmdQdPYo/eeWVIwufON11gmbPmUAB4sA0jKUk=”
如果有人有兴趣,就这样做吧,一切都很好
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);
结果是“sEP5RCWmdQdPYo/eeWVIwg==”
谢谢
如果我们参考https://www.php.net/manual/en/function.openssl-encrypt.php
options 是标志 OPENSSL_RAW_DATA 和 OPENSSL_ZERO_PADDING 的按位或取。
OPENSSL_RAW_DATA = 1(二进制:
01
)
OPENSSL_ZERO_PADDING = 2(二进制:10
)
所以:
base64_encode(openssl_encrypt($plainText, $cipher, $key, 0)); // 00 = no flags
c0VQNVJDV21kUWRQWW8vZWVXVkl3dWZPTjExZ21iUG1VQUI0c0EwaktVaz0=
base64_encode(openssl_encrypt($plainText, $cipher, $key, 1)); // 01 = OPENSSL_RAW_DATA
sEP5RCWmdQdPYo/eeWVIwufON11gmbPmUAB4sA0jKUk=
base64_encode(openssl_encrypt($plainText, $cipher, $key, 2)); // 10 = OPENSSL_ZERO_PADDING
c0VQNVJDV21kUWRQWW8vZWVXVkl3Zz09
base64_encode(openssl_encrypt($plainText, $cipher, $key, 3)); // 11 = OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING
sEP5RCWmdQdPYo/eeWVIwg==
并且该模式会重复,因为我们只寻找最后 2 位
base64_encode(openssl_encrypt($plainText, $cipher, $key, 4)); // (1)00
c0VQNVJDV21kUWRQWW8vZWVXVkl3dWZPTjExZ21iUG1VQUI0c0EwaktVaz0=
base64_encode(openssl_encrypt($plainText, $cipher, $key, 5)); // (1)01
sEP5RCWmdQdPYo/eeWVIwufON11gmbPmUAB4sA0jKUk=
base64_encode(openssl_encrypt($plainText, $cipher, $key, 6)); // (1)10
c0VQNVJDV21kUWRQWW8vZWVXVkl3Zz09
base64_encode(openssl_encrypt($plainText, $cipher, $key, 7)); // (1)11
sEP5RCWmdQdPYo/eeWVIwg==
OPENSSL_RAW_DATA | OPENSSL_DONT_ZERO_PAD_KEY | OPENSSL_ZERO_PADDING = 1 | 4 | 2 = 7 所以我们得到
openssl_encrypt($plainText, $cipher, $key, 7)