/user/8a3f 而非 /user/123)<?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] ✓
<?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);
<?php
use Hashids\Hashids;
$hashids = new Hashids('project-salt', 8, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
$encoded = $hashids->encode(123); // 'jR7x9Kp2'
$decoded = $hashids->decode($encoded); // [123]
<?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 應用的重要一環。