在 Web 開發中,資料加密是保護敏感資訊(如電子郵件驗證連結、API 金鑰)的關鍵手段。本文分享一個輕量級的 PHP 加密解密類 SysCrypt,採用對稱加密演算法,適合快速整合至專案中。
該類別封裝了加密、解密與金鑰處理邏輯,建構子接受自訂金鑰,解構時自動清除敏感資料:
class SysCrypt {
private $crypt_key = 'https://www.example.com'; // 預設金鑰,建議替換為複雜字串
public function __construct($crypt_key) {
$this->crypt_key = $crypt_key;
}
public function encrypt($txt) {
srand((double)microtime() * 1000000);
$encrypt_key = md5(rand(0, 32000));
$ctr = 0;
$tmp = '';
for ($i = 0; $i < strlen($txt); $i++) {
$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
$tmp .= $encrypt_key[$ctr] . ($txt[$i] ^ $encrypt_key[$ctr++]);
}
return base64_encode($this->_key($tmp, $this->crypt_key));
}
public function decrypt($txt) {
$txt = $this->_key(base64_decode($txt), $this->crypt_key);
$tmp = '';
for ($i = 0; $i < strlen($txt); $i++) {
$md5 = $txt[$i];
$tmp .= $txt[++$i] ^ $md5;
}
return $tmp;
}
private function _key($txt, $encrypt_key) {
$encrypt_key = md5($encrypt_key);
$ctr = 0;
$tmp = '';
for ($i = 0; $i < strlen($txt); $i++) {
$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
$tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
}
return $tmp;
}
public function __destruct() {
$this->crypt_key = NULL;
}
}
實例化物件並測試加解密流程:
$sc = new SysCrypt('your_custom_secret_key');
$text = 'user@example.com';
$encrypted = $sc->encrypt($text);
$decrypted = $sc->decrypt($encrypted);
echo "原文:{$text}
";
echo "密文:{$encrypted}
";
echo "解密:{$decrypted}
";
輸出結果:
原文:user@example.com 密文:BS8DbFU6AioCNFFlVGZQMgRGBDUOYlEzBXoAZgo0Bjk= 解密:user@example.com