跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

JavaScript加密算法_Web Crypto API

Web Crypto API 提供浏览器原生加密功能,支持哈希、对称加密、非对称加密等;其核心模块包括 SHA-256 摘要、AES-GCM 加密解密、RSA 密钥生成与签名验证,且需在 HTTPS 环境下使用以确保安全。 Web Crypto API 是现代 浏览器 提供的一套强大的加密功能接口,允许开发者在客户端实现安全的加密操作。它支持多种常见的加密算法,包括哈希、对称加密、非对称加密、数字签名等,所有操作都在浏览器内部完成,无需依赖第三方库,提升了性能和安全性。 支持的主要功能 Web Crypto API 提供了以下几个核心功能模块: 摘要(Hash): 对数据生成固定长度的哈希值,常用算法有 SHA-256、SHA-384、SHA-512。 对称加密(AES): 使用同一密钥进行加密和解密,如 AES-CBC、AES-GCM 模式。 非对称加密(RSA、ECDSA): 支持生成密钥对,用于加密/解密或签名/验证。 密钥管理: 可以生成、导入、导出、派生和使用加密密钥。 随机数生成: 提供安全的随机数生成器( crypto.getRandomValues() )。 基本使用示例 以下是一些常见操作的代码示例,展示如何使用 Web Crypto API 实现基本加密功能。 1. 计算 SHA-256 哈希 立即学习 “ Java免费学习笔记(深入) ”; Comet AI 浏览器 下载 Comet AI 浏览器,体验由 Perplexity AI 驱动的革命性上网方式。内置 AI 助手可实时总结网页、跨标签页对比信息、自动执行任务。告别繁琐操作,让 AI 成为你的浏览副驾,大幅提升研究与工作效率。支持 Windows、macOS、Android 和 iOS。 下载
async function hashData(data) { const encoder = new TextEncoder(); const dataBuffer = encoder.encode(data); const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer); return Array.from(new Uint8Array(hashBuffer)) .map(b => b.toString(16).padStart(2, '0')) .join(''); } // 使用 hashData('Hello, world!').then(console.log); // 输出: a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e
2. 使用 AES-GCM 进行对称加密与解密
async function encryptAES(key, plaintext) { const encoder = new TextEncoder(); const data = encoder.encode(plaintext); const iv = crypto.getRandomValues(new Uint8Array(12)); // GCM 推荐 IV 长度为 12 字节 const encrypted = await crypto.subtle.encrypt( { name: 'AES-GCM', iv }, key, data ); return { encrypted, iv }; } async function decryptAES(key, encryptedData, iv) { const decrypted = await crypto.subtle.decrypt( { name: 'AES-GCM', iv }, key, encryptedData ); const decoder = new TextDecoder(); return decoder.decode(decrypted); } // 生成密钥并使用 crypto.subtle.generateKey( { name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt'] ).then(async (key) => { const { encrypted, iv } = await encryptAES(key, 'Secret message'); const decrypted = await decryptAES(key, encrypted, iv); console.log(decrypted); // 输出: Secret message });
3. 生成 RSA 密钥对并签名/验证
async function generateRSAKeyPair() { return await crypto.subtle.generateKey( { name: 'RSASSA-PKCS1-v1_5', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }, true, ['sign', 'verify'] ); } async function signData(privateKey, data) { const encoder = new TextEncoder(); const encodedData = encoder.encode(data); return await crypto.subtle.sign('RSASSA-PKCS1-v1_5', privateKey, encodedData); } async function verifySignature(publicKey, signature, data) { const encoder = new TextEncoder(); const encodedData = encoder.encode(data); return await crypto.subtle.verify( 'RSASSA-PKCS1-v1_5', publicKey, signature, encodedData ); }
注意事项与限制 虽然 Web Crypto API 功能强大,但在实际使用中需要注意以下几点: 必须在安全上下文中运行(即 HTTPS 或 localhost),否则无法访问 crypto.subtle 。 部分旧浏览器不完全支持某些算法或模式,需做兼容性检查。 密钥通常不能直接导出为明文,只能以特定格式(如 JWK)导出,且受权限控制。 不要在 前端 单独依赖 Web Crypto 实现敏感逻辑,应结合后端验证确保整体安全。 基本上就这些。合理使用 Web Crypto API 能有效提升前端数据处理的安全性,尤其是在密码处理、本地加密存储、身份认证等场景下非常实用。

相关文章