// PHP
$str = '程序員';
echo md5($str); // 72d9adf4944f23e5efde37f6364c126f
// Node.js (預設)
const crypto = require('crypto');
console.log(crypto.createHash('md5').update('程序員').digest('hex'));
// 1b6ad7846ec870e78363d1db4fb2a0ff ← 不同!
const crypto = require('crypto');
function md5(str) {
const hash = crypto.createHash('md5');
hash.update(str, 'utf8'); // 關鍵:明確指定輸入編碼
return hash.digest('hex');
}
console.log(md5('程序員')); // 72d9adf4944f23e5efde37f6364c126f ✅
| 環境 | 預設編碼行為 | 建議做法 |
|---|---|---|
| PHP `md5()` | UTF-8 (內部轉換) | 確保 PHP 檔案儲存為 UTF-8 無 BOM |
| Node.js `crypto` | UTF-8 (但依賴字串實際編碼) | **永遠加 `'utf8'` 參數** |
| Java `MessageDigest` | 平台預設編碼 (常為 UTF-8) | `digest.update(str.getBytes(StandardCharsets.UTF_8))` |
| Python `hashlib.md5()` | 需位元組輸入 | `hashlib.md5(str.encode('utf-8')).hexdigest()` |
| Go `md5.Sum()` | 需位元組切片 | `md5.Sum([]byte(str))` (字串即 UTF-8) |
| C# `MD5.ComputeHash()` | 需位元組陣列 | `Encoding.UTF8.GetBytes(str)` |
.toLowerCase()"test" → 098f6bcd4621d373cade4e832627b4f6 驗證各語言實作**MD5 已被攻破 (碰撞攻擊)**,**嚴禁用於密碼儲存、簽名驗證、完整性檢查**等安全敏感場景。請改用: