登录
首页 >  文章 >  前端

JavaScript加密实战:WebCryptoAPI使用教程

时间:2026-01-13 15:45:43 223浏览 收藏

今天golang学习网给大家带来了《JavaScript加密实战:Web Crypto API应用解析》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~

Web Crypto API 可在浏览器中实现加密、解密、签名和哈希等功能,支持 AES、RSA、SHA 等算法,适用于数据保护与安全通信;需先检测环境支持并建议在 HTTPS 下使用;通过 crypto.subtle.generateKey 可生成 AES 或 RSA 密钥;AES-GCM 模式结合 IV 实现对称加解密,需注意 iv 随机性与传输;RSA-OAEP 用于非对称加密,适合小数据加密如密钥传输;SHA-256 可通过 crypto.subtle.digest 计算数据哈希以校验完整性;实际应用中应结合后端设计安全协议,避免密钥泄露或参数误用。

JavaScript加密算法_Web Crypto API实战应用

Web Crypto API 是现代浏览器提供的一套强大的加密工具,可以直接在前端实现安全的加密、解密、签名和哈希等操作,无需依赖第三方库。它支持多种标准算法,如 AES、RSA、SHA 等,适用于数据保护、身份验证、安全通信等场景。本文将带你实战使用 Web Crypto API 实现常见的加密功能。

1. 检测浏览器支持

在使用 Web Crypto API 之前,先确认当前环境是否支持:

if (window.crypto && window.crypto.subtle) {
  console.log("Web Crypto API 可用");
} else {
  console.error("当前浏览器不支持 Web Crypto API");
}

注意:部分功能在非 HTTPS 环境下可能受限,开发时建议使用本地 HTTPS 服务器测试。

2. 使用 AES-GCM 进行对称加密与解密

AES-GCM 是一种推荐的对称加密方式,提供机密性和完整性验证。以下是一个字符串加密/解密的完整示例:

// 文本转 ArrayBuffer
function textToArrayBuffer(str) {
  return new TextEncoder().encode(str);
}

// ArrayBuffer 转文本
function arrayBufferToText(buffer) {
  return new TextDecoder().decode(buffer);
}

// 生成 AES 密钥(256位)
async function generateKey() {
  return await crypto.subtle.generateKey(
    { name: "AES-GCM", length: 256 },
    true,
    ["encrypt", "decrypt"]
  );
}

// 加密
async function encrypt(plaintext, key) {
  const encoder = new TextEncoder();
  const data = encoder.encode(plaintext);
  const iv = crypto.getRandomValues(new Uint8Array(12)); // GCM 推荐 12 字节 IV

  const encrypted = await crypto.subtle.encrypt(
    { name: "AES-GCM", iv: iv },
    key,
    data
  );

  // 返回 iv 和密文(需一起存储或传输)
  const encryptedArray = new Uint8Array(encrypted);
  const combined = new Uint8Array(iv.length + encryptedArray.length);
  combined.set(iv);
  combined.set(encryptedArray, iv.length);

  return btoa(String.fromCharCode(...combined)); // 转为 Base64 方便传输
}

// 解密
async function decrypt(encryptedData, key) {
  const combined = Uint8Array.from(atob(encryptedData), c => c.charCodeAt(0));
  const iv = combined.slice(0, 12);
  const data = combined.slice(12);

  const decrypted = await crypto.subtle.decrypt(
    { name: "AES-GCM", iv: iv },
    key,
    data
  );

  return new TextDecoder().decode(decrypted);
}

使用示例:

const key = await generateKey();
const ciphertext = await encrypt("Hello, Web Crypto!", key);
console.log("密文:", ciphertext);

const plaintext = await decrypt(ciphertext, key);
console.log("明文:", plaintext);

3. 使用 RSA-OAEP 实现非对称加密

RSA 适合加密小量数据(如密钥),常用于安全传输对称密钥。以下是密钥生成与加解密流程:

// 生成 RSA 密钥对
async function generateRsaKeyPair() {
  return await crypto.subtle.generateKey(
    {
      name: "RSA-OAEP",
      modulusLength: 2048,
      publicExponent: new Uint8Array([1, 0, 1]),
      hash: "SHA-256"
    },
    true,
    ["encrypt", "decrypt"]
  );
}

// 公钥加密
async function rsaEncrypt(plaintext, publicKey) {
  const encoded = textToArrayBuffer(plaintext);
  const encrypted = await crypto.subtle.encrypt(
    { name: "RSA-OAEP" },
    publicKey,
    encoded
  );
  return btoa(String.fromCharCode(...new Uint8Array(encrypted)));
}

// 私钥解密
async function rsaDecrypt(encryptedData, privateKey) {
  const data = Uint8Array.from(atob(encryptedData), c => c.charCodeAt(0));
  const decrypted = await crypto.subtle.decrypt(
    { name: "RSA-OAEP" },
    privateKey,
    data
  );
  return arrayBufferToText(decrypted);
}

4. 数据完整性校验:使用 SHA-256 生成哈希

计算字符串或文件的哈希值,可用于校验数据完整性:

async function computeHash(data) {
  const encoder = new TextEncoder();
  const buffer = encoder.encode(data);
  const hashBuffer = await crypto.subtle.digest("SHA-256", buffer);
  return Array.from(new Uint8Array(hashBuffer))
    .map(b => b.toString(16).padStart(2, "0"))
    .join("");
}

// 示例
const hash = await computeHash("Hello");
console.log("SHA-256:", hash);

基本上就这些。Web Crypto API 提供了开箱即用的安全能力,关键在于正确选择算法和参数。实际项目中,建议结合后端共同设计加密协议,避免密钥暴露或误用。不复杂但容易忽略细节,比如 IV 的随机性、密钥持久化策略等。

本篇关于《JavaScript加密实战:WebCryptoAPI使用教程》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>