萬盛學電腦網

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

PHP 加密解密字串總匯:Discuz! authcode、自訂 encrypt、OpenSSL AES、JWT 實戰

一、Discuz! 經典 authcode(可逆、帶過期時間、動態金鑰)

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    $ckey_length = 4;
    $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
    $cryptkey = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);

    $string = $operation == 'DECODE'
        ? base64_decode(substr($string, $ckey_length))
        : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;

    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = [];
    for ($i = 0; $i <= 255; $i++) $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i]; $box[$i] = $box[$j]; $box[$j] = $tmp;
    }
    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a]; $box[$a] = $box[$j]; $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if ($operation == 'DECODE') {
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) &&
            substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
            return substr($result, 26);
        }
        return '';
    } else {
        return $keyc . str_replace('=', '', base64_encode($result));
    }
}

// 使用
$str = 'abcdef';
$key = 'www.example.com';
$encrypted = authcode($str, 'ENCODE', $key, 0);
$decrypted = authcode($encrypted, 'DECODE', $key, 0);

二、簡易 encrypt 函式(較輕量)

function encrypt($string, $operation, $key = '') {
    $key = md5($key);
    $key_length = strlen($key);
    $string = $operation == 'D' ? base64_decode($string) : substr(md5($string . $key), 0, 8) . $string;
    $string_length = strlen($string);
    $rndkey = $box = [];
    $result = '';
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($key[$i % $key_length]);
        $box[$i] = $i;
    }
    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i]; $box[$i] = $box[$j]; $box[$j] = $tmp;
    }
    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a]; $box[$a] = $box[$j]; $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if ($operation == 'D') {
        return (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) ? substr($result, 8) : '';
    } else {
        return str_replace('=', '', base64_encode($result));
    }
}

三、現代標準:OpenSSL AES-256-GCM(強烈推薦)

function aesEncrypt($data, $key, $iv = '') {
    $iv = $iv ?: random_bytes(16);
    $cipher = 'aes-256-gcm';
    $tag = null;
    $encrypted = openssl_encrypt($data, $cipher, $key, OPENSSL_RAW_DATA, $iv, $tag);
    return base64_encode($iv . $tag . $encrypted);
}

function aesDecrypt($data, $key) {
    $data = base64_decode($data);
    $iv = substr($data, 0, 16);
    $tag = substr($data, 16, 16);
    $encrypted = substr($data, 32);
    return openssl_decrypt($encrypted, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
}

// 使用
$key = hash('sha256', 'my-secret-key', true); // 32 bytes
$encrypted = aesEncrypt('敏感資料', $key);
$decrypted = aesDecrypt($encrypted, $key);

四、JWT (JSON Web Token) 無狀態認證

// 需安裝 firebase/php-jwt: composer require firebase/php-jwt
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$payload = [
    'iss' => 'my-app',
    'sub' => 12345,
    'iat' => time(),
    'exp' => time() + 3600,
    'data' => ['role' => 'admin']
];
$secret = 'super-secret-key';
$jwt = JWT::encode($payload, $secret, 'HS256');

try {
    $decoded = JWT::decode($jwt, new Key($secret, 'HS256'));
    print_r($decoded);
} catch (Exception $e) {
    echo 'Token 無效: ' . $e->getMessage();
}

選型建議

場景推薦方案關鍵點
密碼儲存password_hash()單向、自動鹽值、可調成本
API Token、Session 替代JWT (HS256/RS256)無狀態、攜帶聲明、需防重放
資料加密儲存/傳輸OpenSSL AES-256-GCM認證加密、隨機 IV、標準庫
相容舊系統authcode / encrypt僅維護舊專案,新專案勿用

安全原則

  • 金鑰管理:使用環境變數、金鑰保管箱(HashiCorp Vault、AWS KMS),絕不硬編碼。
  • 隨機 IV:每次加密產生新 IV,隨密文儲存。
  • 認證加密:優先 AES-GCM、ChaCha20-Poly1305,避免 CBC+HMAC 組合錯誤。
  • 時效性:Token 設定合理過期,支援撤銷/黑名單。
copyright © 萬盛學電腦網 all rights reserved