本文展示如何使用 PHP 生成 MD5 雜湊字典(彩虹表),並演示簡易的字典攻擊流程。程式碼以字母(大小寫)與數字為字元集,生成長度 1~4 位的所有組合,計算其 MD5 值並存入檔案,供後續比對破解使用。
$sRand = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$length = strlen($sRand);
if (!($dir = @opendir("/dic"))) {
mkdir("dic", 0777);
}
for ($q = 0; $q < $length; $q++) {
$op = ($q > 25 && $q < 52) ? 'cap' : '';
$fp = fopen("./dic/" . $op . $sRand[$q] . ".txt", "w");
$crack = $sRand[$q];
fputs($fp, $crack . "|" . md5($crack) . " ");
for ($m = 0; $m < $length; $m++) {
$crack = $sRand[$q] . $sRand[$m];
fputs($fp, $crack . "|" . md5($crack) . " ");
for ($l = 0; $l < $length; $l++) {
$crack = $sRand[$q] . $sRand[$m] . $sRand[$l];
fputs($fp, $crack . "|" . md5($crack) . " ");
for ($o = 0; $o < $length; $o++) {
$crack = $sRand[$q] . $sRand[$m] . $sRand[$l] . $sRand[$o];
fputs($fp, $crack . "|" . md5($crack) . " ");
}
}
}
fclose($fp);
}
$afcontent = file("./dic/" . $op . $sRand[$s] . ".txt", "r");
foreach ($afcontent as $sdics) {
$adics = explode("|", $sdics);
if (substr($adics[1], 0, 32) == $md5_pwd) {
// 找到匹配明文
}
}
password_hash() / password_verify()(bcrypt/Argon2)並加鹽,而非單純 MD5。理解彩虹表原理有助於認知雜湊碰撞風險,並強化密碼儲存安全策略。