当前位置:首页 > JavaScript

js rsa 实现

2026-04-06 18:30:25JavaScript

RSA 加密算法实现

RSA 是一种非对称加密算法,广泛应用于数据加密和数字签名。以下是 JavaScript 实现 RSA 加密和解密的方法。

生成 RSA 密钥对

使用 crypto.subtle.generateKey 方法生成 RSA 密钥对:

async function generateRSAKeyPair() {
  const keyPair = await window.crypto.subtle.generateKey(
    {
      name: "RSA-OAEP",
      modulusLength: 2048,
      publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
      hash: "SHA-256",
    },
    true,
    ["encrypt", "decrypt"]
  );
  return keyPair;
}
  • modulusLength: 密钥长度,通常为 2048 或 4096。
  • publicExponent: 公钥指数,默认使用 [0x01, 0x00, 0x01](即 65537)。
  • hash: 哈希算法,支持 SHA-1、SHA-256、SHA-384 或 SHA-512。

加密数据

使用公钥加密数据:

async function encryptData(publicKey, data) {
  const encodedData = new TextEncoder().encode(data);
  const encryptedData = await window.crypto.subtle.encrypt(
    {
      name: "RSA-OAEP",
    },
    publicKey,
    encodedData
  );
  return encryptedData;
}
  • data: 需要加密的字符串或二进制数据。
  • 返回的 encryptedDataArrayBuffer 类型。

解密数据

使用私钥解密数据:

async function decryptData(privateKey, encryptedData) {
  const decryptedData = await window.crypto.subtle.decrypt(
    {
      name: "RSA-OAEP",
    },
    privateKey,
    encryptedData
  );
  return new TextDecoder().decode(decryptedData);
}
  • encryptedData: 加密后的 ArrayBuffer 数据。
  • 返回解密后的原始字符串。

导出和导入密钥

导出公钥

async function exportPublicKey(publicKey) {
  const exported = await window.crypto.subtle.exportKey("spki", publicKey);
  return window.btoa(String.fromCharCode(...new Uint8Array(exported)));
}

导入公钥

async function importPublicKey(base64Key) {
  const binaryKey = Uint8Array.from(atob(base64Key), c => c.charCodeAt(0));
  return await window.crypto.subtle.importKey(
    "spki",
    binaryKey,
    {
      name: "RSA-OAEP",
      hash: "SHA-256",
    },
    true,
    ["encrypt"]
  );
}

导出私钥

async function exportPrivateKey(privateKey) {
  const exported = await window.crypto.subtle.exportKey("pkcs8", privateKey);
  return window.btoa(String.fromCharCode(...new Uint8Array(exported)));
}

导入私钥

async function importPrivateKey(base64Key) {
  const binaryKey = Uint8Array.from(atob(base64Key), c => c.charCodeAt(0));
  return await window.crypto.subtle.importKey(
    "pkcs8",
    binaryKey,
    {
      name: "RSA-OAEP",
      hash: "SHA-256",
    },
    true,
    ["decrypt"]
  );
}

示例代码

以下是一个完整的 RSA 加密解密示例:

js rsa 实现

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

  // 导出公钥和私钥
  const publicKeyBase64 = await exportPublicKey(keyPair.publicKey);
  const privateKeyBase64 = await exportPrivateKey(keyPair.privateKey);

  console.log("Public Key:", publicKeyBase64);
  console.log("Private Key:", privateKeyBase64);

  // 加密数据
  const originalData = "Hello, RSA!";
  const encryptedData = await encryptData(keyPair.publicKey, originalData);

  // 解密数据
  const decryptedData = await decryptData(keyPair.privateKey, encryptedData);
  console.log("Decrypted Data:", decryptedData);
}

runRSADemo();

注意事项

  1. 密钥长度:RSA 密钥长度至少为 2048 位以确保安全性。
  2. 性能:RSA 加密和解密操作较慢,不适合加密大量数据。
  3. 浏览器支持crypto.subtle API 在现代浏览器中支持较好,但在某些旧版本中可能不可用。
  4. 密钥存储:私钥必须安全存储,避免泄露。

如果需要更高级的功能(如签名和验证),可以使用 signverify 方法。

标签: jsrsa
分享给朋友:

相关文章

js实现日历

js实现日历

实现日历的基本思路 使用JavaScript实现日历的核心是动态生成日期表格,并处理月份切换逻辑。需要计算当前月的天数、起始星期几,并动态渲染到页面上。 获取当前日期信息 通过Date对象获取当前年…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js实现目录

js实现目录

实现目录的基本思路 在JavaScript中实现目录功能通常涉及以下几个核心步骤:解析文档中的标题元素(如h1-h6),动态生成目录结构,并添加交互逻辑(如点击跳转)。以下是具体实现方法: 解析标题…

js实现轮播代码

js实现轮播代码

基础轮播实现 使用HTML、CSS和JavaScript创建一个简单的轮播效果。HTML部分定义轮播容器和图片元素。 <div class="carousel"> <div c…

js 实现日历

js 实现日历

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

js 实现截图

js 实现截图

使用html2canvas库实现截图 html2canvas是一个流行的JavaScript库,可将HTML元素转换为Canvas,进而导出为图片。 安装库: npm install ht…