js实现sha1加密
JavaScript 实现 SHA-1 加密
SHA-1(Secure Hash Algorithm 1)是一种常用的哈希算法,用于生成数据的唯一哈希值。在 JavaScript 中,可以通过原生 API 或第三方库实现 SHA-1 加密。
使用 Web Crypto API(原生支持)
现代浏览器支持 Web Crypto API,可以直接调用 crypto.subtle.digest 方法生成 SHA-1 哈希值。
async function sha1(message) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-1', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
// 使用示例
sha1('Hello World').then(console.log); // 输出: 0a4d55a8d778e5022fab701977c5d840bbc486d0
使用第三方库(如 js-sha1)
如果需要在旧版浏览器或 Node.js 环境中使用,可以引入第三方库 js-sha1。
安装库(Node.js):
npm install js-sha1
使用示例:
const sha1 = require('js-sha1');
const hash = sha1('Hello World');
console.log(hash); // 输出: 0a4d55a8d778e5022fab701977c5d840bbc486d0
浏览器中直接引入 js-sha1
通过 CDN 引入:
<script src="https://cdn.jsdelivr.net/npm/js-sha1@0.6.0/src/sha1.min.js"></script>
<script>
const hash = sha1('Hello World');
console.log(hash); // 输出: 0a4d55a8d778e5022fab701977c5d840bbc486d0
</script>
注意事项
- SHA-1 已被证明存在安全性问题,不推荐用于密码存储或敏感数据加密。建议使用更安全的算法(如 SHA-256 或 SHA-3)。
- Web Crypto API 仅支持 HTTPS 或本地环境(
localhost),非安全上下文中可能无法使用。







