本文介紹一個模仿 ASP 中 Mistake 算法實現的 PHP 自定義加密函數。由於 PHP 的 rand() 行為與 ASP 的 Randomize/Rnd 不同,加密結果會有差異,但邏輯結構可供參考學習。
<?php
function customEncrypt($str) {
$i = 1;
$length = 0;
$str = trim($str);
$length = strlen($str);
$seed = $length;
srand($length); // 以字符串長度作為種子
$texts = '';
for ($i; $i <= $length; $i++) {
// 複雜的種子運算
$seed = intval(94 * rand(0, -ord(substr($str, $i, 1)) - $seed * ord(substr($str, 1, -1))) + 32);
$texts .= ord($seed) . ord(intval(94 * ord(-$seed) + 32));
}
echo ord($texts);
}
?>
ord($texts),即將拼接後的字符串首字符 ASCII 碼輸出,實際應用中通常需返回完整字符串。<?php
class LegacyEncryptor {
private $seed;
public function encrypt(string $plaintext): string {
$plaintext = trim($plaintext);
$len = strlen($plaintext);
$this->seed = $len;
srand($len);
$result = '';
for ($i = 1; $i <= $len; $i++) {
$charCode = ord(substr($plaintext, $i - 1, 1)); // PHP 索引從 0 開始
$lastCharCode = ord(substr($plaintext, 0, 1));
$this->seed = intval(94 * rand(0, -$charCode - $this->seed * $lastCharCode) + 32);
$result .= chr($this->seed) . chr(intval(94 * ord(-$this->seed) + 32));
}
return $result;
}
}
// 使用示例
$encryptor = new LegacyEncryptor();
$encrypted = $encryptor->encrypt('Hello World');
echo '加密結果: ' . bin2hex($encrypted); // 以十六進制顯示非可見字符
?>
rand() 非加密安全隨機數生成器,種子可預測。openssl_encrypt()、sodium_crypto_secretbox() 等經驗證的加密庫。<?php
// 使用 OpenSSL AES-256-CBC 加密
function modernEncrypt(string $data, string $key): string {
$iv = random_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$ciphertext = openssl_encrypt($data, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
return base64_encode($iv . $ciphertext);
}
function modernDecrypt(string $encryptedData, string $key): ?string {
$data = base64_decode($encryptedData);
$ivLen = openssl_cipher_iv_length('aes-256-cbc');
$iv = substr($data, 0, $ivLen);
$ciphertext = substr($data, $ivLen);
return openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
}
$key = hash('sha256', 'my-secret-password', true); // 32 字節密鑰
$encrypted = modernEncrypt('敏感數據', $key);
echo "加密: $encrypted\n";
echo "解密: " . modernDecrypt($encrypted, $key);
?>
理解舊代碼邏輯有助於維護遺留系統,但新項目務必採用業界標準加密方案。本文提供的改進版封裝了原邏輯,並給出現代最佳實踐對比,供開發者參考選擇。