当前位置:首页 > JavaScript

js实现rsa加密

2026-04-04 09:15:22JavaScript

RSA加密的基本原理

RSA是一种非对称加密算法,基于大整数分解的数学难题。它使用公钥加密数据,私钥解密数据,常用于数据传输加密和数字签名。

生成RSA密钥对

使用JavaScript生成RSA密钥对通常需要借助Web Crypto API:

js实现rsa加密

async function generateKeyPair() {
  return await window.crypto.subtle.generateKey(
    {
      name: "RSA-OAEP",
      modulusLength: 2048,
      publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
      hash: "SHA-256"
    },
    true,
    ["encrypt", "decrypt"]
  );
}

公钥加密数据

使用公钥加密字符串数据:

async function encryptData(publicKey, data) {
  const encoded = new TextEncoder().encode(data);
  return await window.crypto.subtle.encrypt(
    {
      name: "RSA-OAEP"
    },
    publicKey,
    encoded
  );
}

私钥解密数据

使用私钥解密加密后的数据:

js实现rsa加密

async function decryptData(privateKey, encryptedData) {
  const decrypted = await window.crypto.subtle.decrypt(
    {
      name: "RSA-OAEP"
    },
    privateKey,
    encryptedData
  );
  return new TextDecoder().decode(decrypted);
}

完整示例流程

async function rsaExample() {
  // 生成密钥对
  const keyPair = await generateKeyPair();

  // 原始数据
  const originalData = "Secret message";

  // 加密
  const encrypted = await encryptData(keyPair.publicKey, originalData);
  console.log("Encrypted:", new Uint8Array(encrypted));

  // 解密
  const decrypted = await decryptData(keyPair.privateKey, encrypted);
  console.log("Decrypted:", decrypted);
}

注意事项

Web Crypto API只能在安全上下文(HTTPS或localhost)中使用。对于Node.js环境,可以使用crypto模块:

const crypto = require('crypto');

function nodeRsaEncrypt(publicKey, data) {
  return crypto.publicEncrypt(
    {
      key: publicKey,
      padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
      oaepHash: 'sha256'
    },
    Buffer.from(data)
  );
}

密钥格式处理

实际应用中可能需要处理PEM格式的密钥:

// 从PEM字符串导入公钥
async function importPublicKey(pem) {
  const pemHeader = "-----BEGIN PUBLIC KEY-----";
  const pemFooter = "-----END PUBLIC KEY-----";
  const pemContents = pem.substring(
    pemHeader.length,
    pem.length - pemFooter.length
  );
  const binaryDer = atob(pemContents);
  return await window.crypto.subtle.importKey(
    "spki",
    str2ab(binaryDer),
    { name: "RSA-OAEP", hash: "SHA-256" },
    true,
    ["encrypt"]
  );
}

// 字符串转ArrayBuffer
function str2ab(str) {
  const buf = new ArrayBuffer(str.length);
  const bufView = new Uint8Array(buf);
  for (let i = 0; i < str.length; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

性能考虑

RSA加密适合加密少量数据(如加密对称密钥)。对于大量数据,建议使用RSA加密对称密钥,再用对称密钥加密数据。

标签: jsrsa
分享给朋友:

相关文章

js如何实现继承

js如何实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例能够访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js实现列表

js实现列表

使用 JavaScript 实现列表 JavaScript 提供了多种方式来实现列表功能,包括数组操作、DOM 元素动态生成等。以下是几种常见的实现方法: 使用数组存储列表数据 数组是 JavaSc…

js防抖和节流实现

js防抖和节流实现

防抖(Debounce)的实现 防抖的核心思想是在事件被触发后,延迟执行回调函数。如果在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口大小调整等场景。 function debounce…

js实现密码

js实现密码

密码强度验证 使用正则表达式验证密码强度是一种常见方法。以下代码检查密码是否包含大小写字母、数字和特殊字符,且长度至少为8位: function checkPasswordStrength(pass…

js图片上传实现

js图片上传实现

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API实现基础图片上传功能。HTML部分需要设置accept="image/…

js 实现日历

js 实现日历

实现日历的基本思路 日历的核心功能是展示日期,并允许用户进行日期选择或导航。JavaScript 可以动态生成日历的 HTML 结构,并处理用户交互逻辑。 基础日历结构 日历通常包含头部(显示月份和…