萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 自定義可逆加密解密類(教學演示級)

本文展示一個基於字符映射表的自定義雙向加密類 Crypto,通過密碼生成動態替換字母表實現字符級替換加密。警告:此算法屬教學演示級,安全性極低,嚴禁用於生產環境敏感數據加密! 生產環境請使用 AES-256-GCM、ChaCha20-Poly1305 等經驗證的認證加密算法。

算法原理

  1. 定義基礎字符集 $ralphabet(大小寫字母、數字、符號)。
  2. 構造雙倍字符集 $alphabet = $ralphabet . $ralphabet 便於循環取子串。
  3. 密碼每個字符在 $alphabet 中定位,取其後 strlen($ralphabet) 字符作為該位的替換表。
  4. 加密:明文字符在 $ralphabet 中的位置,對應替換表同位置字符作為密文字符。
  5. 解密:密文字符在替換表中定位,對應 $ralphabet 同位置字符還原明文。
  6. 密碼循環使用,實現類 Vigenère 密碼效果。

完整類代碼

<?php
$ralphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !,.:;?~@#$%^&*()_+-=][}{/><\"'";
$alphabet = $ralphabet . $ralphabet;

class Crypto {
    public function encrypt($password, $strToEncrypt) {
        global $ralphabet, $alphabet;
        $tables = $this->buildTables($password);
        return $this->transform($strToEncrypt, $tables, $ralphabet, true);
    }

    public function decrypt($password, $strToDecrypt) {
        global $ralphabet, $alphabet;
        $tables = $this->buildTables($password);
        return $this->transform($strToDecrypt, $tables, $ralphabet, false);
    }

    private function buildTables($password) {
        global $alphabet, $ralphabet;
        $tables = [];
        for ($i = 0; $i < strlen($password); $i++) {
            $ch = $password[$i];
            $pos = strpos($alphabet, $ch);
            if ($pos === false) $pos = 0; // 密碼字符不在表中默認 0
            $tables[] = substr($alphabet, $pos, strlen($ralphabet));
        }
        return $tables;
    }

    private function transform($str, $tables, $ralphabet, $encrypt) {
        $result = '';
        $n = count($tables);
        for ($i = 0; $i < strlen($str); $i++) {
            $table = $tables[$i % $n];
            $ch = $str[$i];
            if ($encrypt) {
                $idx = strpos($ralphabet, $ch);
                $result .= ($idx !== false) ? $table[$idx] : $ch; // 不在表中字符保持不變
            } else {
                $idx = strpos($table, $ch);
                $result .= ($idx !== false) ? $ralphabet[$idx] : $ch;
            }
        }
        return $result;
    }

    // 生成加密表格(調試用)
    public function printTable($password) {
        global $ralphabet, $alphabet;
        $tables = $this->buildTables($password);
        echo "<table border=1 cellpadding=0 cellspacing=0>\n<tr><td></td>";
        for ($j=0;$j$t) {
            echo "<tr><td align=right>".($i+1)."|</td>";
            for ($k=0;$kencrypt($_POST['password'], $_POST['strtoencrypt']);
    echo "加密結果: <input value='".htmlspecialchars($enc)."' size=60>";
    echo " 密鑰: <input name='password' value='".htmlspecialchars($_POST['password'])."' size=10>";
    echo " <button onclick=\"location.href=''\">解密</button>";
} else {
    $dec = $ct->decrypt($_POST['password'], $_POST['strtodecrypt']);
    echo "解密結果: <input value='".htmlspecialchars($dec)."' size=60>";
    echo " 密鑰: <input name='password' value='".htmlspecialchars($_POST['password'])."' size=10>";
    echo " <input type=hidden name=mod value=2> <button onclick=\"location.href=''\">加密</button>";
}
?>

安全性分析(為何不可用於生產)

生產環境正確選擇

// 推薦:libsodium (PHP 7.2+ 內建) - 認證加密
$key = sodium_crypto_secretbox_keygen(); // 32字節,需安全保存
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); // 24字節,每次加密唯一
$ciphertext = sodium_crypto_secretbox($message, $nonce, $key);
// 存儲:nonce + ciphertext (Base64編碼)

// 解密
$decrypted = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
if ($decrypted === false) throw new Exception('認證失敗,數據被篡改');
  • 對稱加密:sodium_crypto_secretbox (XChaCha20-Poly1305) 或 openssl_encrypt(..., 'aes-256-gcm')。
  • 非對稱加密:sodium_crypto_box (Curve25519-XSalsa20-Poly1305) 或 openssl_encrypt 配合 RSA/OAEP。
  • 密碼派生:sodium_crypto_pwhash (Argon2id) 或 password_hash() (bcrypt)。
  • 密鑰管理:使用 Vault、AWS KMS、HashiCorp Vault 等專業密鑰管理系統。

理解自定義加密原理有助於學習密碼學基礎,但實際項目必須使用經過廣泛審計、標準化的加密庫,切勿自行實現。

copyright © 萬盛學電腦網 all rights reserved
弱點說明
密鑰空間小僅依賴密碼字符在 68 字符表中的位置,易暴力破解。
無完整性校驗密文可被篡改且解密後無法檢測(無 MAC/認證標籤)。
無隨機性相同明文+密鑰恆產生相同密文,洩露模式信息。
字符集固定無法加密字符集外字符(如中文、換行符),實際應用嚴重受限。
抗攻擊未經驗證未經學術界密碼分析,可能存在未知弱點(如關聯攻擊、選擇明文攻擊)。