萬盛學電腦網

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

PHP 數字專用加密解密類:ID 隱藏、URL 安全傳輸、資料庫主鍵保護

應用場景

  • URL 中隱藏真實資料庫 ID (如 /user/8a3f 而非 /user/123)
  • API 回傳資料時混淆內部主鍵
  • 前端傳遞參數防止遍歷攻擊
  • 分享連結不洩露業務數量級

演算法原理

  1. 字元表打亂:62 個字元 (a-z, A-Z, 0-9) 經金鑰衍生打亂
  2. 長度標記:第一字元編碼原始數字長度 (1-9 位)
  3. 數字替換:每位數字映射至打亂字元表對應位置
  4. 隨機填充:剩餘長度填充干擾字元,固定輸出長度

完整類別實作

<?php
/**
 * 數字加密解密器
 * 輸出固定長度字串,包含:長度標記 + 填充干擾 + 數字替換
 */
class NumericCipher {
    private string $charset;
    private string $lenMarker;   // 長度標記字元集 (前 $length 字元)
    private string $digitMap;    // 數字 0-9 映射字元 (第 $length+1 到 $length+10)
    private string $padding;     // 填充字元集 (剩餘)
    private int $length;         // 固定輸出長度
    private float $key;          // 干擾金鑰

    public function __construct(int $length = 9, float $key = 2543.5415412812) {
        $this->length = $length;
        $this->key = $key;

        // 基礎字元表 (可自定義種子打亂)
        $base = 'Flpvf70CsakVjqgeWUPXQxSyJizmNH6B1u3b8cAEKwTd54nRtZOMDhoG2YLrI';
        // 生產環境建議:用 key 衍生打亂,而非固定字串
        $this->charset = $base;

        $this->lenMarker = substr($this->charset, 0, $this->length);
        $this->digitMap  = substr($this->charset, $this->length, 10);
        $this->padding   = substr($this->charset, $this->length + 10);
    }

    /** 加密:數字字串 → 固定長度密文 */
    public function encode(string $number): string {
        if (!ctype_digit($number)) throw new InvalidArgumentException('Only digits allowed');

        $numLen = strlen($number);
        if ($numLen > $this->length - 1) throw new OverflowException('Number too long');

        // 1. 長度標記 (第 1 字元)
        $result = $this->lenMarker[$numLen - 1];

        // 2. 填充干擾 (長度 = 總長 - 1 - 數字長)
        $padLen = $this->length - $numLen - 1;
        if ($padLen > 0) {
            // 用數字/金鑰產生偽隨機填充
            $seed = str_replace('.', '', (string)($number / $this->key));
            $seed = substr($seed, -$padLen);
            $padChars = str_split($this->padding);
            foreach (str_split($seed) as $digit) {
                $result .= $padChars[$digit] ?? $padChars[0];
            }
        }

        // 3. 數字替換
        $digitChars = str_split($this->digitMap);
        foreach (str_split($number) as $digit) {
            $result .= $digitChars[$digit];
        }

        return $result;
    }

    /** 解密:密文 → 原始數字字串 */
    public function decode(string $cipher): string {
        if (strlen($cipher) !== $this->length) return '';

        // 1. 解析長度標記
        $marker = $cipher[0];
        $pos = strpos($this->lenMarker, $marker);
        if ($pos === false) return '';
        $numLen = $pos + 1;

        // 2. 取出數字部分 (最後 $numLen 字元)
        $digitPart = substr($cipher, -$numLen);
        $digitChars = str_split($this->digitMap);
        $result = '';

        foreach (str_split($digitPart) as $char) {
            $pos = strpos($this->digitMap, $char);
            if ($pos === false) return '';
            $result .= $pos;
        }

        return $result;
    }
}

// 測試
$cipher = new NumericCipher(9);
for ($i = 9950; $i < 10000; $i++) {
    $enc = $cipher->encode((string)$i);
    $dec = $cipher->decode($enc);
    echo "[$i] → [$enc] → [$dec]" . ($i === (int)$dec ? ' ✓' : ' ✗') . "\n";
}

輸出範例

[9950] → [vmizxPPga] → [9950] ✓
[9951] → [vSNSSPPgk] → [9951] ✓
[9952] → [vNQNyPPgV] → [9952] ✓
...
[9999] → [vQQQQPPgz] → [9999] ✓

安全性分析與改進

現有實作弱點

  • 固定字元表:原始碼洩露即可破解所有密文
  • 無完整性驗證:密文被竄改解密後仍可能得到合法數字
  • 金鑰硬編碼:無法輪換、無法每用戶/每請求不同
  • 非加密標準:屬於「混淆」而非加密,不提供機密性

生產級替代方案

方案 A:Laravel/Illuminate Encrypter (AES-256-CBC + MAC)

<?php
use Illuminate\Encryption\Encrypter;
use Illuminate\Support\Str;

$key = base64_decode(config('app.key')); // 32 bytes
$encrypter = new Encrypter($key, 'AES-256-CBC');

$encrypted = $encrypter->encryptString((string)$id); // 含 IV + MAC
$decrypted = (int)$encrypter->decryptString($encrypted);

方案 B:Hashids (短唯一 ID,非加密但不可逆推導)

<?php
use Hashids\Hashids;

$hashids = new Hashids('project-salt', 8, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
$encoded = $hashids->encode(123); // 'jR7x9Kp2'
$decoded = $hashids->decode($encoded); // [123]

方案 C:JWT (含過期、簽名、載荷)

<?php
use Firebase\JWT\JWT;

$payload = ['uid' => 123, 'exp' => time() + 3600];
$token = JWT::encode($payload, $secret, 'HS256');
$data = JWT::decode($token, new Key($secret, 'HS256'));

選型建議

需求推薦方案特點
單純隱藏 ID、短連結Hashids無狀態、可解碼、短、可自定義字元集
需機密性、防竄改、過期JWT / Encrypter標準加密、攜帶額外資訊、需金鑰管理
內部系統、低風險、極簡依賴本類別 (改進版)零依賴、固定長度、可自定義字元表

改進版本類別 (支援金鑰衍生字元表)

<?php
class SecureNumericCipher {
    private string $lenMarker;
    private string $digitMap;
    private string $padding;
    private int $length;

    public function __construct(int $length = 12, string $secret = '') {
        $this->length = $length;
        // 使用密鑰衍生字元表 (簡易版,生產請用 HKDF)
        $seed = hash('sha256', $secret . 'charset', true);
        $base = '';
        for ($i = 0; $i < 62; $i++) {
            $base .= chr(($seed[$i % 32] ?? 0) % 62 + 48); // 簡易映射
        }
        // 確保 62 個唯一字元 (實際應用用 Fisher-Yates 洗牌)
        $this->lenMarker = substr($base, 0, $length);
        $this->digitMap  = substr($base, $length, 10);
        $this->padding   = substr($base, $length + 10);
    }
    // encode/decode 邏輯同上...
}

選擇正確的工具保護數字標識符,是構建安全 Web 應用的重要一環。

copyright © 萬盛學電腦網 all rights reserved