「自定義加密」在學習階段有助理解原理,**嚴禁用於生產環境敏感數據**(密碼、Token、支付信息)。生產環境必須使用**經過學術界驗證、廣泛審計的標準算法**。本文展示教學級替換加密、Base64 變體,並給出 **OpenSSL AES-256-GCM (AEAD)** 生產級實現。
password_hash() (bcrypt/argon2),數據加密用 openssl_encrypt() AES-256-GCM 或 sodium_crypto_aead_* (libsodium)。
<?php
/**
* 簡單替換密碼 (Substitution Cipher) - 僅供教學演示
* 缺陷:頻率分析可破解、無完整性驗證、密鑰管理困難
*/
class SimpleSubstitutionCipher
{
private string $alphabet;
private string $cipherAlphabet;
private array $encryptMap = [];
private array $decryptMap = [];
public function __construct(string $key = '')
{
// 基礎字符集:可打印 ASCII
$this->alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=[]{}|;:,.<>?';
// 使用密鑰打亂字符集 (簡易演示,真正應用需 CSPRNG)
$this->cipherAlphabet = $this->shuffleAlphabet($this->alphabet, $key);
// 構建映射表
for ($i = 0; $i < strlen($this->alphabet); $i++) {
$this->encryptMap[$this->alphabet[$i]] = $this->cipherAlphabet[$i];
$this->decryptMap[$this->cipherAlphabet[$i]] = $this->alphabet[$i];
}
}
private function shuffleAlphabet(string $alphabet, string $key): string
{
$arr = str_split($alphabet);
// 簡單種子打亂 (不安全,演示用)
$seed = crc32($key);
mt_srand($seed);
shuffle($arr);
return implode('', $arr);
}
public function encrypt(string $plaintext): string
{
$result = '';
for ($i = 0; $i < strlen($plaintext); $i++) {
$ch = $plaintext[$i];
$result .= $this->encryptMap[$ch] ?? $ch; // 不在字符集內保持原樣
}
return $result;
}
public function decrypt(string $ciphertext): string
{
$result = '';
for ($i = 0; $i < strlen($ciphertext); $i++) {
$ch = $ciphertext[$i];
$result .= $this->decryptMap[$ch] ?? $ch;
}
return $result;
}
}
// 測試
$cipher = new SimpleSubstitutionCipher('my-secret-key');
$encrypted = $cipher->encrypt('Hello World! 123');
$decrypted = $cipher->decrypt($encrypted);
echo "Encrypted: $encrypted\nDecrypted: $decrypted\n";
function customEncode(string $data, string $key): string
{
// 1. Base64 編碼
$encoded = base64_encode($data);
// 2. 基於密鑰打亂 Base64 字符表
$base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
$shuffled = str_shuffle($base64Chars); // 注意:str_shuffle 不可用於加密,這裡僅演示
// 真正應用應用 HMAC(key) 衍生確定性打亂表
$map = array_combine(str_split($base64Chars), str_split($shuffled));
$result = strtr($encoded, $map);
// 3. 添加版本標識
return 'CUSTOMv1:' . $result;
}
function customDecode(string $encoded, string $key): string
{
if (!str_starts_with($encoded, 'CUSTOMv1:')) return '';
$encoded = substr($encoded, 9);
$base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
$shuffled = str_shuffle($base64Chars); // 必須與加密時一致!這裡無法實現,演示缺陷
$map = array_combine(str_split($shuffled), str_split($base64Chars));
$decoded = strtr($encoded, $map);
return base64_decode($decoded, true) ?: '';
}
AEAD (Authenticated Encryption with Associated Data) 同時提供**機密性**、**完整性**、**認證性**。AES-256-GCM 是現代標準 (TLS 1.3、Signal、WhatsApp 均使用)。
<?php
/**
* 生產級加密工具類
* 算法: AES-256-GCM (AEAD)
* 密鑰: 32 字節 (256 bit)
* Nonce: 12 字節 (96 bit, 每次加密必須唯一)
* Tag: 16 字節 (認證標簽)
*/
class AeadCrypt
{
private string $cipher = 'aes-256-gcm';
private int $keyLength = 32; // 256 bit
private int $nonceLength = 12; // 96 bit, GCM 標準
private int $tagLength = 16; // 128 bit
/** 從密碼派生密鑰 (PBKDF2) */
public static function deriveKey(string $password, string $salt, int $iterations = 100000): string
{
return hash_pbkdf2('sha256', $password, $salt, $keyLength, $iterations, true);
}
/** 加密
* @return string Base64 編碼: version(1B) + salt(16B) + nonce(12B) + ciphertext + tag(16B)
*/
public function encrypt(string $plaintext, string $password, string $associatedData = ''): string
{
// 1. 生成隨機鹽值 (用於密鑰派生)
$salt = random_bytes(16);
// 2. 派生密鑰
$key = self::deriveKey($password, $salt);
// 3. 生成隨機 Nonce (每次加密必須唯一!)
$nonce = random_bytes($this->nonceLength);
// 4. 加密
$ciphertext = '';
$tag = '';
$len = openssl_encrypt(
$plaintext,
$this->cipher,
$key,
OPENSSL_RAW_DATA,
$nonce,
$tag,
$associatedData,
$this->tagLength
);
if ($len === false) {
throw new \RuntimeException('Encryption failed: ' . openssl_error_string());
}
// 5. 組合輸出: version(1) + salt(16) + nonce(12) + ciphertext + tag(16)
// 版本號為將來算法升級預留
return base64_encode("\x01" . $salt . $nonce . $ciphertext . $tag);
}
/** 解密 */
public function decrypt(string $payload, string $password, string $associatedData = ''): string
{
$data = base64_decode($payload, true);
if ($data === false) throw new \RuntimeException('Invalid base64');
// 1. 解析結構
if (strlen($data) < 1 + 16 + 12 + 16) {
throw new \RuntimeException('Payload too short');
}
$version = $data[0];
if ($version !== "\x01") throw new \RuntimeException('Unsupported version');
$salt = substr($data, 1, 16);
$nonce = substr($data, 17, 12);
$tag = substr($data, -16);
$ciphertext = substr($data, 29, -16);
// 2. 派生密鑰
$key = self::deriveKey($password, $salt);
// 3. 解密並驗證 Tag
$plaintext = openssl_decrypt(
$ciphertext,
$this->cipher,
$key,
OPENSSL_RAW_DATA,
$nonce,
$tag,
$associatedData
);
if ($plaintext === false) {
throw new \RuntimeException('Decryption failed: authentication tag mismatch or corrupted data');
}
return $plaintext;
}
}
// ========== 使用示例 ==========
$crypt = new AeadCrypt();
$password = 'user-master-password-from-config'; // 實際應從安全配置中心讀取
$associatedData = 'user-id:123'; // 綁定上下文,防止密文移花接木
// 加密
$encrypted = $crypt->encrypt('敏感數據:身份證 1234567890', $password, $associatedData);
echo "Encrypted: $encrypted\n";
// 解密
try {
$decrypted = $crypt->decrypt($encrypted, $password, $associatedData);
echo "Decrypted: $decrypted\n";
} catch (Exception $e) {
echo "Decrypt failed: " . $e->getMessage() . "\n"; // 篡改密文/關聯數據會在此拋出異常
}
**密碼不加密,只哈希!** PHP 內置最佳實踐:
<?php
// 註冊:哈希密碼
$hash = password_hash($password, PASSWORD_ARGON2ID); // PHP 7.2+ 推薦 Argon2id
// 或 PASSWORD_BCRYPT (成本因子 12+)
// $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
// 存入數據庫 $hash (長度 60+ 字符,包含算法、成本、鹽值)
// 登錄:驗證
if (password_verify($inputPassword, $hash)) {
// 成功
// 檢查是否需要重新哈希 (算法升級、成本增加)
if (password_needs_rehash($hash, PASSWORD_ARGON2ID)) {
$newHash = password_hash($inputPassword, PASSWORD_ARGON2ID);
// 更新數據庫
}
}
| 用途 | 推薦方案 | PHP 函數/庫 | 關鍵點 |
|---|---|---|---|
| 用戶密碼 | 單向哈希 (不可逆) | password_hash/verify (Argon2id/Bcrypt) | 自帶鹽值、成本因子、升級機制 |
| API Token、Session ID | 隨機生成 + 資料庫存儲哈希 | random_bytes(32) + hash('sha256', $token) | Token 本身不加密,驗證時比較哈希 |
| 敏感配置 (API Key、私鑰) | 對稱加密 AES-256-GCM | openssl_encrypt/decrypt 或 sodium_crypto_aead_* | 密鑰輪換、關聯數據綁定上下文 |
| 數據庫字段加密 (PII) | AEAD 加密 | 同上,或使用 Laravel Encrypter / Symfony Secrets | 列級加密、索引需求用確定性加密(特殊) |
| 文件加密 | 流式 AEAD (分塊) | sodium_crypto_secretstream_* | 大文件分塊加密,每塊帶 Tag |
| 教學/CTF/非敏感混淆 | Base64 + 自定義映射 | 自寫函數 | **不可用於任何真實安全場景** |
記住:**加密是專業密碼學家的工作,開發者的職責是正確選用、配置、管理標準庫**。PHP 7.2+ 提供了完整的現代密碼學原語,請直接使用它們。