js实现mac
实现 MAC(消息认证码)的 JavaScript 方法
在 JavaScript 中实现 MAC(Message Authentication Code)通常需要使用加密库或原生 API。以下是两种常见的方法:
使用 Web Crypto API(浏览器环境)
Web Crypto API 是现代浏览器提供的原生加密接口,支持 HMAC(Hash-based MAC)算法:

async function generateHMAC(message, secretKey) {
const encoder = new TextEncoder();
const messageBuffer = encoder.encode(message);
const keyBuffer = encoder.encode(secretKey);
const cryptoKey = await window.crypto.subtle.importKey(
'raw',
keyBuffer,
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
);
const signature = await window.crypto.subtle.sign(
'HMAC',
cryptoKey,
messageBuffer
);
return Array.from(new Uint8Array(signature))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
使用 Node.js 的 crypto 模块
在 Node.js 环境中可以使用内置的 crypto 模块:

const crypto = require('crypto');
function generateHMAC(message, secretKey) {
return crypto
.createHmac('sha256', secretKey)
.update(message)
.digest('hex');
}
注意事项
- 密钥长度应足够长(推荐至少 32 字节)
- 选择适当的哈希算法(如 SHA-256)
- 浏览器环境中 Web Crypto API 仅支持 HTTPS 或 localhost
- 存储密钥时应确保安全性
验证 MAC 的方法
验证 MAC 时只需重新计算 MAC 并与接收到的 MAC 比较:
async function verifyHMAC(message, receivedMAC, secretKey) {
const calculatedMAC = await generateHMAC(message, secretKey);
return calculatedMAC === receivedMAC;
}
其他 MAC 算法
除了 HMAC,还可以实现:
- CMAC(基于分组密码)
- Poly1305(通常与 ChaCha20 配合使用)
但这些算法在 JavaScript 中通常需要第三方库支持。






