本文介紹一個功能完善的 PHP 加密解密類 Ender,採用動態隨機密鑰配合 Base64 編碼,並處理特殊字符替換,適合 API 簽名、Token 生成、敏感數據傳輸等場景。
= 為自定義字符(默認 #),避免 URL 傳輸問題<?php
class Ender {
private $enkey; // 主加密密鑰
private $rep_char = '#'; // Base64 填充字符替換
public function __construct($key = '') {
$this->enkey = $key;
}
public function set_key($key) {
$this->enkey = $key;
}
/** 核心異或運算 */
private function keyED($txt, $encrypt_key) {
$encrypt_key = md5($encrypt_key);
$ctr = 0;
$tmp = "";
for ($i = 0; $i < strlen($txt); $i++) {
if ($ctr == strlen($encrypt_key)) $ctr = 0;
$tmp .= substr($txt, $i, 1) ^ substr($encrypt_key, $ctr, 1);
$ctr++;
}
return $tmp;
}
/** 加密入口 */
public function encrypt($txt, $key = '') {
if (!$key) $key = $this->enkey;
srand((double)microtime() * 1000000);
$encrypt_key = md5(rand(0, 32000)); // 隨機一次性密鑰
$ctr = 0;
$tmp = "";
for ($i = 0; $i < strlen($txt); $i++) {
if ($ctr == strlen($encrypt_key)) $ctr = 0;
// 交織隨機密鑰字符與異或結果
$tmp .= substr($encrypt_key, $ctr, 1) . (substr($txt, $i, 1) ^ substr($encrypt_key, $ctr, 1));
$ctr++;
}
// 主密鑰二次加密 + Base64 + 字符替換
$r = base64_encode($this->keyED($tmp, $key));
$r = str_replace('=', $this->rep_char, $r);
return $r;
}
/** 解密入口 */
public function decrypt($txt, $key = '') {
$txt = str_replace($this->rep_char, '=', $txt); // 還原填充字符
$txt = base64_decode($txt);
if (!$key) $key = $this->enkey;
$txt = $this->keyED($txt, $key); // 主密鑰解密
$tmp = "";
for ($i = 0; $i < strlen($txt); $i++) {
$md5 = substr($txt, $i, 1); // 提取隨機密鑰字符
$i++;
$tmp .= (substr($txt, $i, 1) ^ $md5); // 異或還原明文
}
return $tmp;
}
}
?>
<?php
require_once 'Ender.php';
$ender = new Ender('my_secret_key_2024');
$original = '敏感數據:用戶ID=12345,金額=999.99';
$encrypted = $ender->encrypt($original);
echo "加密結果: $encrypted\n";
$decrypted = $ender->decrypt($encrypted);
echo "解密結果: $decrypted\n";
// 驗證
assert($original === $decrypted, '加解密不一致');
md5(rand()) → a1b2c3...aH1e2b3l4l5o6...keyED() 再次異或= 替換為 ## → =| 特性 | 說明 |
|---|---|
| 抗重放攻擊 | 每次加密使用隨機密鑰,相同明文產生不同密文 |
| 密鑰分離 | 傳輸密鑰與存儲密鑰分離,洩露隨機密鑰無法破解主密鑰 |
| 字符安全 | 自動處理 Base64 特殊字符,適合 URL/JSON 傳輸 |
| 對稱加密 | 同一密鑰加解密,需妥善保管主密鑰 |
此類庫代碼結構清晰,易於擴展(如添加 HMAC 完整性校驗、支援更多字符集),是 PHP 專案中快速集成加密功能的不錯選擇。