当前位置:首页 > JavaScript

js实现rsa

2026-04-06 05:38:29JavaScript

RSA 加密算法简介

RSA 是一种非对称加密算法,广泛应用于数据加密和数字签名。它基于大数分解的数学难题,安全性依赖于大整数分解的困难性。RSA 包含密钥生成、加密和解密三个主要步骤。

生成 RSA 密钥对

在 JavaScript 中可以使用 crypto.subtle API 生成 RSA 密钥对。以下是一个生成 RSA-OAEP 密钥对的示例:

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;
}

加密数据

使用公钥加密数据时,需要将数据转换为 ArrayBuffer 格式:

js实现rsa

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;
}

解密数据

使用私钥解密数据时,同样需要处理 ArrayBuffer 格式:

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

导出和导入密钥

密钥可以导出为可传输或存储的格式(如 JWK 或 PEM):

js实现rsa

async function exportKey(key, format = 'jwk') {
  const exported = await window.crypto.subtle.exportKey(format, key);
  return exported;
}

async function importPublicKey(jwkKey) {
  const publicKey = await window.crypto.subtle.importKey(
    'jwk',
    jwkKey,
    {
      name: "RSA-OAEP",
      hash: "SHA-256",
    },
    true,
    ["encrypt"]
  );
  return publicKey;
}

注意事项

  • RSA-OAEP 是推荐的填充方案,比 PKCS#1 v1.5 更安全。
  • 密钥长度至少应为 2048 位,更高的安全性需要 3072 或 4096 位。
  • 浏览器环境中的 crypto.subtle API 仅在 HTTPS 或 localhost 下可用。

完整示例

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

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

  // 导出公钥
  const publicKeyJwk = await exportKey(keyPair.publicKey);

  // 模拟传输公钥
  const importedPublicKey = await importPublicKey(publicKeyJwk);

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

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

runExample();

Node.js 环境实现

在 Node.js 中可以使用 crypto 模块实现 RSA:

const crypto = require('crypto');

// 生成密钥对
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem'
  }
});

// 加密
function encrypt(publicKey, data) {
  return crypto.publicEncrypt(publicKey, Buffer.from(data));
}

// 解密
function decrypt(privateKey, encryptedData) {
  return crypto.privateDecrypt(privateKey, encryptedData).toString();
}

// 示例
const encrypted = encrypt(publicKey, 'Secret message');
const decrypted = decrypt(privateKey, encrypted);
console.log(decrypted);

标签: jsrsa
分享给朋友:

相关文章

js实现预览

js实现预览

文件上传预览实现 使用JavaScript实现文件上传预览功能,可以通过FileReader对象读取文件内容并显示预览。以下代码支持图片、文本和PDF文件的预览: // HTML部分需要包含inpu…

js实现跑马灯

js实现跑马灯

实现跑马灯效果 使用HTML和JavaScript可以轻松实现跑马灯效果。以下是两种常见的实现方式: HTML结构 <div id="marquee"> <span>…

js 实现图片 放大

js 实现图片 放大

使用 CSS transform 实现图片放大 通过 CSS 的 transform: scale() 属性可以实现图片的平滑放大效果。结合 JavaScript 监听鼠标事件控制放大状态: con…

js实现左右滑动

js实现左右滑动

实现左右滑动的 JavaScript 方法 监听触摸事件 通过 touchstart、touchmove 和 touchend 事件来检测用户的手势操作。记录触摸的起始位置和移动距离,判断滑动方向。…

js实现刷新页面

js实现刷新页面

刷新页面的方法 在JavaScript中,可以通过多种方式实现页面刷新。以下是几种常见的方法: 使用 location.reload() 调用 location.reload() 方法可以重新加载当…

js实现点击隐藏

js实现点击隐藏

使用CSS类切换实现点击隐藏 通过添加或移除CSS类来控制元素的显示与隐藏。定义一个隐藏样式类如.hidden { display: none; },通过事件监听切换该类。 document.que…