首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 實用加密解密類:輕鬆實現資料安全傳輸

     編輯:PHP 相關知識

在 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

安全性建議

  • 生產環境務必替換預設金鑰,使用高熵值隨機字串
  • 考慮搭配 OpenSSL 的 AES-256-GCM 等現代加密方式以提升安全等級
  • 避免在前端或日誌中輸出密文,防止被逆向分析
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved