js 实现md5加密
MD5加密的JavaScript实现方法
使用现代JavaScript实现MD5加密可以通过原生API或第三方库完成。以下是几种常见方法:
使用Web Crypto API(原生支持)
现代浏览器支持的原生加密API,性能最佳且无需依赖第三方库:
async function md5(message) {
const msgBuffer = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('MD5', msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
// 使用示例
md5('hello').then(hexDigest => console.log(hexDigest));
使用SparkMD5库
轻量级专门处理MD5的库,适合浏览器环境:
// 先引入SparkMD5库:<script src="https://cdnjs.cloudflare.com/ajax/libs/spark-md5/3.0.2/spark-md5.min.js"></script>
const hash = SparkMD5.hash('hello world');
console.log(hash); // 输出32字符MD5值
使用crypto-js库
功能更全面的加密库,支持多种哈希算法:
// 安装:npm install crypto-js
import MD5 from 'crypto-js/md5';
const hash = MD5('message').toString();
console.log(hash);
纯JavaScript实现
不依赖任何库的完整实现(代码较长,适合理解原理):
function md5(string) {
// 初始化变量和常量
let [a, b, c, d] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476];
const k = new Array(64).fill(0).map((_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296));
// 字符串预处理
const msg = encodeUTF8(string);
const len = msg.length * 8;
msg.push(0x80);
while ((msg.length * 8) % 512 !== 448) msg.push(0x00);
msg.push(...int64ToBytes(len));
// 分块处理
for (let i = 0; i < msg.length; i += 64) {
const chunk = msg.slice(i, i + 64);
[a, b, c, d] = processChunk(chunk, a, b, c, d, k);
}
// 输出结果
return toHex(a) + toHex(b) + toHex(c) + toHex(d);
}
// 辅助函数需自行实现:encodeUTF8, int64ToBytes, processChunk, toHex等
注意事项
- MD5已被证明存在碰撞漏洞,不适合安全敏感场景
- 浏览器原生API仅支持HTTPS环境或localhost
- Node.js环境可直接使用
crypto模块:const crypto = require('crypto'); const hash = crypto.createHash('md5').update('hello').digest('hex');







