需要的時候,MD5 可以在瀏覽器端就完成,不必來回伺服器一躺。做法是引入 jQuery 與 md5 外掛,然後直接呼叫即可:
$.md5("你想要加密的字符串");
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>MD5 Demo</title>
<script type="text/javascript" src="Scripts/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.md5.js"></script>
<script type="text/javascript">
alert($.md5("Hello"));
</script>
</head>
<body>
</body>
</html>
載入順序要注意:jquery.md5.js 依賴 jQuery 物件,必須放在 jQuery 之後,否則會出現 $.md5 is not a function 這類錯誤。
這個外掛可以勝任諸如「避免快取破壞」、「產生簡單校驗碼」這類非安全用途,但不能當作密碼保護手段,原因有兩個:
因此,前端 MD5 的合理定位是「傳輸前的簡單擾亂」或「表單資料完整性參考」,真正的身分驗證仍然必須在伺服器端進行,並且要使用 bcrypt、scrypt 或 Argon2 這類專為密碼設計、具備加鹽與慢速特性的演算法。