当前位置:首页 > JavaScript

js实现加密

2026-02-01 12:37:51JavaScript

使用 Web Crypto API 进行加密

Web Crypto API 是现代浏览器提供的原生加密接口,支持 AES、RSA、SHA 等算法。以下示例展示如何使用 AES-GCM 加密数据:

async function encryptAES(text, password) {
  const encoder = new TextEncoder();
  const data = encoder.encode(text);

  const salt = crypto.getRandomValues(new Uint8Array(16));
  const keyMaterial = await crypto.subtle.importKey(
    'raw',
    encoder.encode(password),
    { name: 'PBKDF2' },
    false,
    ['deriveKey']
  );

  const key = await crypto.subtle.deriveKey(
    {
      name: 'PBKDF2',
      salt: salt,
      iterations: 100000,
      hash: 'SHA-256'
    },
    keyMaterial,
    { name: 'AES-GCM', length: 256 },
    false,
    ['encrypt']
  );

  const iv = crypto.getRandomValues(new Uint8Array(12));
  const encrypted = await crypto.subtle.encrypt(
    { name: 'AES-GCM', iv: iv },
    key,
    data
  );

  return {
    ciphertext: Array.from(new Uint8Array(encrypted)),
    iv: Array.from(iv),
    salt: Array.from(salt)
  };
}

使用 SJCL 库加密

Stanford JavaScript Crypto Library (SJCL) 是轻量级加密库,适合需要兼容旧浏览器的场景:

// 引入 SJCL 库后
function encryptWithSJCL(plaintext, password) {
  const ciphertext = sjcl.encrypt(password, plaintext, {
    iter: 10000,
    ks: 256,
    ts: 128,
    mode: 'gcm'
  });
  return ciphertext;
}

RSA 非对称加密实现

使用 Web Crypto API 生成密钥对并加密:

async function generateRSAKeys() {
  const keyPair = await crypto.subtle.generateKey(
    {
      name: 'RSA-OAEP',
      modulusLength: 2048,
      publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
      hash: 'SHA-256'
    },
    true,
    ['encrypt', 'decrypt']
  );

  return {
    publicKey: await crypto.subtle.exportKey('jwk', keyPair.publicKey),
    privateKey: await crypto.subtle.exportKey('jwk', keyPair.privateKey)
  };
}

async function rsaEncrypt(publicKey, data) {
  const key = await crypto.subtle.importKey(
    'jwk',
    publicKey,
    { name: 'RSA-OAEP', hash: 'SHA-256' },
    false,
    ['encrypt']
  );

  const encrypted = await crypto.subtle.encrypt(
    { name: 'RSA-OAEP' },
    key,
    new TextEncoder().encode(data)
  );

  return Array.from(new Uint8Array(encrypted));
}

哈希函数示例

使用 SHA-256 生成消息摘要:

async function hashSHA256(message) {
  const msgBuffer = new TextEncoder().encode(message);
  const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}

注意事项

所有加密操作应在 HTTPS 环境下进行,确保传输安全。敏感密钥应妥善存储,避免硬编码在客户端代码中。Web Crypto API 仅在安全上下文(Secure Context)中可用。

js实现加密

对于生产环境,建议结合后端服务进行密钥管理和更复杂的加密流程。浏览器端加密应作为安全链中的一环,而非唯一保障。

标签: js
分享给朋友:

相关文章

原生js实现轮播图

原生js实现轮播图

基本结构搭建 HTML部分需要包含轮播图容器、图片列表及导航按钮。结构示例如下: <div class="slider-container"> <div class="slid…

js实现pdf在线预览

js实现pdf在线预览

使用PDF.js实现PDF在线预览 PDF.js是由Mozilla开发的一个开源JavaScript库,可以在网页中直接渲染PDF文件。以下是实现PDF在线预览的步骤: 引入PDF.js库 在HT…

使用js实现

使用js实现

使用JavaScript实现 JavaScript可以通过Math.random()函数生成随机数,结合其他方法可以实现多种随机数生成需求。 // 生成0到1之间的随机小数 const random…

vue实现js休眠

vue实现js休眠

实现 JavaScript 休眠的方法 在 Vue 中实现 JavaScript 休眠(延迟执行)可以通过以下方式实现。由于 JavaScript 本身没有内置的 sleep 函数,通常使用 Prom…

js实现vue路由

js实现vue路由

Vue 路由的基本实现 在 Vue.js 中实现路由功能通常使用 Vue Router 库。Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue R…

js实现正交

js实现正交

正交的概念 正交在数学和计算机科学中通常指两个向量垂直或线性无关。在编程中,正交性常被用于设计模块化、低耦合的系统。 向量正交判断 判断两个向量是否正交可以通过点积是否为0来实现: functio…