本文展示一個基於字符映射表的自定義雙向加密類 Crypto,通過密碼生成動態替換字母表實現字符級替換加密。警告:此算法屬教學演示級,安全性極低,嚴禁用於生產環境敏感數據加密! 生產環境請使用 AES-256-GCM、ChaCha20-Poly1305 等經驗證的認證加密算法。
$ralphabet(大小寫字母、數字、符號)。$alphabet = $ralphabet . $ralphabet 便於循環取子串。$alphabet 中定位,取其後 strlen($ralphabet) 字符作為該位的替換表。$ralphabet 中的位置,對應替換表同位置字符作為密文字符。$ralphabet 同位置字符還原明文。<?php
$ralphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !,.:;?~@#$%^&*()_+-=][}{/><\"'";
$alphabet = $ralphabet . $ralphabet;
class Crypto {
public function encrypt($password, $strToEncrypt) {
global $ralphabet, $alphabet;
$tables = $this->buildTables($password);
return $this->transform($strToEncrypt, $tables, $ralphabet, true);
}
public function decrypt($password, $strToDecrypt) {
global $ralphabet, $alphabet;
$tables = $this->buildTables($password);
return $this->transform($strToDecrypt, $tables, $ralphabet, false);
}
private function buildTables($password) {
global $alphabet, $ralphabet;
$tables = [];
for ($i = 0; $i < strlen($password); $i++) {
$ch = $password[$i];
$pos = strpos($alphabet, $ch);
if ($pos === false) $pos = 0; // 密碼字符不在表中默認 0
$tables[] = substr($alphabet, $pos, strlen($ralphabet));
}
return $tables;
}
private function transform($str, $tables, $ralphabet, $encrypt) {
$result = '';
$n = count($tables);
for ($i = 0; $i < strlen($str); $i++) {
$table = $tables[$i % $n];
$ch = $str[$i];
if ($encrypt) {
$idx = strpos($ralphabet, $ch);
$result .= ($idx !== false) ? $table[$idx] : $ch; // 不在表中字符保持不變
} else {
$idx = strpos($table, $ch);
$result .= ($idx !== false) ? $ralphabet[$idx] : $ch;
}
}
return $result;
}
// 生成加密表格(調試用)
public function printTable($password) {
global $ralphabet, $alphabet;
$tables = $this->buildTables($password);
echo "<table border=1 cellpadding=0 cellspacing=0>\n<tr><td></td>";
for ($j=0;$j$t) {
echo "<tr><td align=right>".($i+1)."|</td>";
for ($k=0;$kencrypt($_POST['password'], $_POST['strtoencrypt']);
echo "加密結果: <input value='".htmlspecialchars($enc)."' size=60>";
echo " 密鑰: <input name='password' value='".htmlspecialchars($_POST['password'])."' size=10>";
echo " <button onclick=\"location.href=''\">解密</button>";
} else {
$dec = $ct->decrypt($_POST['password'], $_POST['strtodecrypt']);
echo "解密結果: <input value='".htmlspecialchars($dec)."' size=60>";
echo " 密鑰: <input name='password' value='".htmlspecialchars($_POST['password'])."' size=10>";
echo " <input type=hidden name=mod value=2> <button onclick=\"location.href=''\">加密</button>";
}
?>
| 弱點 | 說明 |
|---|---|
| 密鑰空間小 | 僅依賴密碼字符在 68 字符表中的位置,易暴力破解。 |
| 無完整性校驗 | 密文可被篡改且解密後無法檢測(無 MAC/認證標籤)。 |
| 無隨機性 | 相同明文+密鑰恆產生相同密文,洩露模式信息。 |
| 字符集固定 | 無法加密字符集外字符(如中文、換行符),實際應用嚴重受限。 |
| 抗攻擊未經驗證 | 未經學術界密碼分析,可能存在未知弱點(如關聯攻擊、選擇明文攻擊)。 |