This commit is contained in:
2025-11-18 13:38:05 +08:00
parent a3e5568f93
commit f9062837ab
7 changed files with 286 additions and 116 deletions

View File

@@ -44,6 +44,114 @@ if (!function_exists('d')) {
/**
* 加密函数带随机字符AES-256-CBC
* @param string $plaintext 待加密明文(如字符串、数字)
* @param string $key 加密密钥(建议至少 8 位,越复杂越安全)
* @return string|false 加密后的密文(失败返回 false
*/
function simple_encrypt(string $plaintext, string $key): string|false
{
try {
// 1. 生成随机字符Salt + IV
$salt = random_bytes(8); // 8 位随机盐值(增加密钥多样性)
$iv = random_bytes(16); // 16 位随机 IVAES-256-CBC 块大小要求)
// 2. 密钥处理Salt + 原始密钥 → SHA256 哈希 → 32 位密钥AES-256 要求)
$encryptedKey = hash('sha256', $salt . $key, true); // true 表示返回二进制数据
// 3. 明文填充PKCS7 填充AES 要求明文长度是块大小的整数倍)
$blockSize = openssl_cipher_iv_length('aes-256-cbc');
$padding = $blockSize - (strlen($plaintext) % $blockSize);
$paddedPlaintext = $plaintext . str_repeat(chr($padding), $padding);
// 4. AES 加密(返回 Base64 编码的密文)
$ciphertext = openssl_encrypt(
$paddedPlaintext,
'aes-256-cbc',
$encryptedKey,
OPENSSL_RAW_DATA, // 输出原始二进制数据(后续手动 Base64
$iv
);
if ($ciphertext === false) {
throw new Exception('加密失败:' . openssl_error_string());
}
// 5. 拼接 Salt + IV + 密文Base64 编码后用冒号分隔,避免字符冲突)
return base64_encode($salt) . ':' . base64_encode($iv) . ':' . base64_encode($ciphertext);
} catch (Exception $e) {
error_log('加密异常:' . $e->getMessage());
return false;
}
}
/**
* 解密函数(对应 simple_encrypt
* @param string $ciphertext 加密后的密文
* @param string $key 解密密钥(必须与加密密钥一致)
* @return string|false 解密后的明文(失败返回 false
*/
function simple_decrypt(string $ciphertext, string $key): string|false
{
try {
// 1. 拆分密文Salt:IV:密文(按冒号分割)
$parts = explode(':', $ciphertext);
if (count($parts) !== 3) {
throw new Exception('密文格式错误');
}
// 2. Base64 解码,获取原始 Salt、IV、密文
$salt = base64_decode($parts[0]);
$iv = base64_decode($parts[1]);
$ciphertextRaw = base64_decode($parts[2]);
if ($salt === false || $iv === false || $ciphertextRaw === false) {
throw new Exception('Base64 解码失败');
}
// 3. 密钥处理(与加密时一致)
$encryptedKey = hash('sha256', $salt . $key, true);
// 4. AES 解密
$paddedPlaintext = openssl_decrypt(
$ciphertextRaw,
'aes-256-cbc',
$encryptedKey,
OPENSSL_RAW_DATA,
$iv
);
if ($paddedPlaintext === false) {
throw new Exception('解密失败:' . openssl_error_string());
}
// 5. 去除 PKCS7 填充
$padding = ord(substr($paddedPlaintext, -1));
$plaintext = substr($paddedPlaintext, 0, -$padding);
return $plaintext;
} catch (Exception $e) {
error_log('解密异常:' . $e->getMessage());
return false;
}
}
/**
* 多维数组去重并重新索引
* @param array $array 待处理的多维数组