You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React.js中实现与Node.js一致的RSA公钥加密功能?

在React中实现兼容Node.js的RSA-OAEP公钥加密

当然可以在React(浏览器环境)中实现与你Node.js服务端匹配的encryptWithPublicKey方法,浏览器端可通过Web Crypto API实现RSA-PKCS1-OAEP填充、SHA-256作为OAEP哈希的加密逻辑,完全能和你现有的Node.js私钥解密流程兼容。

实现代码

以下是React项目中可直接使用的实现:

/**
 * 用RSA公钥加密数据,兼容Node.js端的RSA_PKCS1_OAEP_PADDING + sha256配置
 * @param {string} plainText - 要加密的明文
 * @param {string} publicKeyPem - PEM格式的公钥(如"-----BEGIN PUBLIC KEY-----...-----END PUBLIC KEY-----")
 * @returns {Promise<string>} 加密后的Base64字符串
 */
const encryptWithPublicKey = async (plainText, publicKeyPem) => {
  // 处理PEM公钥,转换为Web Crypto API可识别的格式
  const publicKeyDer = publicKeyPem
    .replace(/-----BEGIN PUBLIC KEY-----/, '')
    .replace(/-----END PUBLIC KEY-----/, '')
    .replace(/\s+/g, '');
  
  const publicKeyBuffer = Uint8Array.from(atob(publicKeyDer), c => c.charCodeAt(0));
  
  // 导入公钥
  const publicKey = await window.crypto.subtle.importKey(
    'spki',
    publicKeyBuffer,
    {
      name: 'RSA-OAEP',
      hash: 'SHA-256'
    },
    false,
    ['encrypt']
  );
  
  // 将明文转换为ArrayBuffer
  const plainTextBuffer = new TextEncoder().encode(plainText);
  
  // 执行加密
  const encryptedBuffer = await window.crypto.subtle.encrypt(
    {
      name: 'RSA-OAEP'
    },
    publicKey,
    plainTextBuffer
  );
  
  // 将加密结果转换为Base64字符串(和Node端输出格式一致)
  return btoa(String.fromCharCode(...new Uint8Array(encryptedBuffer)));
};

使用示例

在React组件中可这样调用:

// 假设从环境变量或接口获取公钥
const PUBLIC_KEY = process.env.REACT_APP_CRYPT_PUBLIC_KEY.replace(/\\n/g, '\n');

// 加密示例
const handleEncrypt = async () => {
  try {
    const encryptedKey = await encryptWithPublicKey('要加密的内容', PUBLIC_KEY);
    console.log('加密结果:', encryptedKey);
    // 可将encryptedKey发送给Node.js服务端解密
  } catch (err) {
    console.error('加密失败:', err);
  }
};

关键匹配点说明

  1. 填充与哈希:Web Crypto API的RSA-OAEP对应Node.js的RSA_PKCS1_OAEP_PADDING,指定hash: 'SHA-256'和Node端的oaepHash: 'sha256'完全匹配。
  2. 输出格式:加密结果转换为Base64字符串,和你Node端encryptedKey.toString('base64')的输出格式一致,服务端可直接用decryptWithPrivateKey方法解密。
  3. 公钥处理:需将PEM格式的公钥去除头尾标识和空格,转换为ArrayBuffer后导入,这是Web Crypto API的要求。

内容的提问来源于stack exchange,提问作者D. Rattansingh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 23:45:13