local function pkcs7_padding(text)
local text_length = #text
local amount_to_pad = 32 - (text_length % 32)
if amount_to_pad == 0 then
amount_to_pad = 32
end
local padding = ""
local pad = string.char(amount_to_pad)
for i = 1, amount_to_pad do
padding = padding .. pad
end
return text .. padding
end
local function encrypt ()
text = "Really"
local key = "11345678901234561234567890123456"
local iv = "1234567890123456"
text = pkcs7_padding(text)
ngx.print("pkcs7: " .. str.to_hex(text))
ngx.print("<br>")
local aes_256_cbc_with_iv = assert(
aes:new(
key,
nil,
aes.cipher(256,"cbc"),
{iv=iv}
)
)
-- AES 128 CBC with IV and no SALT
local encrypted = aes_256_cbc_with_iv:encrypt(text)
ngx.print('encrypted: ' .. str.to_hex(encrypted))
ngx.exit(200)
end
openresty 输出:
pkcs7: 5265616c6c791a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a
encrypted: 0cdcd2f5ac84043d32daa0401ab3026a3fd2f7a9bd7dd5ba62a6ce82f8bc544a47ad9cec4105f500a67d8996fd30b1e3
php 输出:
pkcs7: 5265616c6c791a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a
encrypted: 0cdcd2f5ac84043d32daa0401ab3026a3fd2f7a9bd7dd5ba62a6ce82f8bc544a
php 源码
<?php
$key = '11345678901234561234567890123456';
$iv = '1234567890123456';
$text = 'Really';
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
//使用自定义的填充方式对明文进行补位填充
$pkc_encoder = new PKCS7Encoder();
$text = $pkc_encoder->encode($text);
echo 'pkcs7: ' . bin2hex($text);
echo '<br/>';
mcrypt_generic_init($module, $key, $iv);
//加密
$encrypted = mcrypt_generic($module, $text);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
echo 'encrypted: ' . bin2hex($encrypted);
exit();
class PKCS7Encoder
{
public static $block_size = 32;
public function encode($text)
{
$block_size = self::$block_size;
$text_length = strlen($text);
//计算需要填充的位数
$amount_to_pad = self::$block_size - ($text_length % self::$block_size);
if ($amount_to_pad == 0) {
$amount_to_pad = self::block_size;
}
//获得补位所用的字符
$pad_chr = chr($amount_to_pad);
$tmp = '';
for ($index = 0; $index < $amount_to_pad; $index++) {
$tmp .= $pad_chr;
}
return $text . $tmp;
}
}