You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
1.6 KiB

2 months ago
<?php
namespace LaneWeChat\Core\Aes; // 定义命名空间,用于组织代码
2 months ago
class PKCS7Encoder // 定义PKCS7Encoder类
2 months ago
{
public static $block_size = 32; // 定义PKCS7编码的块大小固定为32字节
2 months ago
// 编码方法用于对数据进行PKCS7填充
2 months ago
function encode($text)
{
$block_size = PKCS7Encoder::$block_size; // 获取块大小
$text_length = strlen($text); // 获取原始数据长度
// 计算需要填充的字节数,使数据长度成为块大小的整数倍
2 months ago
$amount_to_pad = PKCS7Encoder::$block_size - ($text_length % PKCS7Encoder::$block_size);
// 如果数据长度已经是块大小的整数倍,则需要填充一个块大小的字节
2 months ago
if ($amount_to_pad == 0) {
$amount_to_pad = PKCS7Encoder::block_size;
}
$pad_chr = chr($amount_to_pad); // 将需要填充的字节数转换为字符
$tmp = ""; // 初始化临时字符串,用于构建填充字符
2 months ago
for ($index = 0; $index < $amount_to_pad; $index++) {
$tmp .= $pad_chr; // 重复填充字符
2 months ago
}
// 返回填充后的数据
2 months ago
return $text . $tmp;
}
// 解码方法用于移除PKCS7填充
2 months ago
function decode($text)
{
$pad = ord(substr($text, -1)); // 获取最后一个字符的ASCII值即填充的字节数
// 如果填充的字节数不在1到32之间则认为没有填充
2 months ago
if ($pad < 1 || $pad > 32) {
$pad = 0;
}
// 返回移除填充后的数据
2 months ago
return substr($text, 0, (strlen($text) - $pad));
}
}
?>