萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 正則驗證 MD5 哈希值格式的最簡實現

MD5 哈希值固定為 32 位十六進制字符 (0-9, a-f)。本文提供最簡驗證函數、邊界測試案例與擴展應用場景。

核心驗證函數

<?php
/**
 * 驗證字符串是否為標準 MD5 格式
 * @param string $hash 待驗證字符串
 * @return bool
 */
function isMd5(string $hash): bool {
    // 嚴格匹配:32 位小寫十六進制
    return preg_match('/^[a-f0-9]{32}$/i', $hash) === 1;
}

// 等價寫法 (不區分大小寫)
function isMd5CaseInsensitive(string $hash): bool {
    return (bool)preg_match('/^[a-f0-9]{32}$/i', $hash);
}

// 等價寫法 (僅小寫)
function isMd5Lowercase(string $hash): bool {
    return (bool)preg_match('/^[a-f0-9]{32}$/', $hash);
}

測試用例矩陣

輸入預期說明
e10adc3949ba59abbe56e057f20f883e✅ true標準 MD5 ("123456")
E10ADC3949BA59ABBE56E057F20F883E✅ true (i 修飾符)大寫十六進制
e10adc3949ba59abbe56e057f20f883❌ false31 位,長度不足
e10adc3949ba59abbe56e057f20f883ez❌ false33 位,長度超出
e10adc3949ba59abbe56e057f20f883g❌ false包含非十六進制字符 g
e10adc3949ba59abbe56e057f20f883_❌ false包含下劃線
❌ false空字符串
not-a-hash❌ false普通字符串

擴展:驗證其他常見哈希格式

<?php
class HashValidator {
    public static function isMd5(string $hash): bool {
        return preg_match('/^[a-f0-9]{32}$/i', $hash) === 1;
    }
    
    public static function isSha1(string $hash): bool {
        return preg_match('/^[a-f0-9]{40}$/i', $hash) === 1;
    }
    
    public static function isSha256(string $hash): bool {
        return preg_match('/^[a-f0-9]{64}$/i', $hash) === 1;
    }
    
    public static function isSha512(string $hash): bool {
        return preg_match('/^[a-f0-9]{128}$/i', $hash) === 1;
    }
    
    public static function isBcrypt(string $hash): bool {
        // $2y$10$... / $2a$10$... / $2b$10$...
        return preg_match('/^\$2[aby]\$\d{2}\$[./A-Za-z0-9]{53}$/', $hash) === 1;
    }
    
    public static function isArgon2id(string $hash): bool {
        // $argon2id$v=19$m=65536,t=3,p=4$...
        return str_starts_with($hash, '$argon2id$');
    }
    
    /** 通用驗證:算法 + 哈希 */
    public static function validate(string $algorithm, string $hash): bool {
        return match (strtolower($algorithm)) {
            'md5' => self::isMd5($hash),
            'sha1' => self::isSha1($hash),
            'sha256' => self::isSha256($hash),
            'sha512' => self::isSha512($hash),
            'bcrypt' => self::isBcrypt($hash),
            'argon2id' => self::isArgon2id($hash),
            default => false,
        };
    }
}

// 使用
var_dump(HashValidator::isMd5('e10adc3949ba59abbe56e057f20f883e'));  // true
var_dump(HashValidator::validate('sha256', 'ef92b7...'));  // true/false

安全提示:MD5 不適用於密碼存儲

⚠️ 重要警告:MD5 是加密哈希函數,非密碼哈希函數。特徵:速度極快、無鹽值、可彩虹表破解、GPU 秒級碰撞。
  • ❌ md5($password) 存儲密碼
  • ❌ md5($salt . $password) 手工加鹽
  • ✅ password_hash($password, PASSWORD_BCRYPT) 或 PASSWORD_ARGON2ID
  • ✅ password_verify($input, $storedHash) 驗證

性能微優化

<?php
// 避免正則編譯開銷:預編譯或靜態緩存
class FastHashValidator {
    private static array $patterns = [];
    
    private static function getPattern(string $regex): int {
        return self::$patterns[$regex] ??= @preg_match($regex, '');  // 預熱/緩存 (實際用靜態變量存 Pattern 物件更佳)
    }
    
    public static function isMd5(string $hash): bool {
        // PHP 8.0+ 可用 preg_match 緩存優化,或直接用 ctype_xdigit + strlen
        return strlen($hash) === 32 && ctype_xdigit($hash);  // 🚀 最快:無正則開銷
    }
}

// ctype_xdigit 專門檢測十六進制字符,C 級實現,極快
function isMd5Fastest(string $hash): bool {
    return strlen($hash) === 32 && ctype_xdigit($hash);
}

總結

驗證 MD5 格式:strlen($hash) === 32 && ctype_xdigit($hash) 是最高性能、零依賴、語義最清晰的方案。正則版本 /^[a-f0-9]{32}$/i 適合需要統一正則風格的代碼庫。切記:MD5 僅用於完整性校驗、非敏感標識生成,嚴禁用於密碼存儲。

copyright © 萬盛學電腦網 all rights reserved