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

前端与API间RSA加解密遇DecryptionFail错误求助

RSA加密后Python解密失败(DecryptionFail)的解决方案

问题根源

Node.js crypto.publicEncrypt 默认使用 RSA_PKCS1_OAEP_PADDING 填充,而Python rsa 库的 decrypt 方法默认使用 PKCS#1 v1.5 填充,两者填充方式不匹配是解密失败的核心原因。此外,密钥加载的格式细节也可能影响兼容性。

解决方案

方案1:统一使用PKCS#1 v1.5填充(修改Node.js加密代码)

在Node.js/TypeScript加密时明确指定填充方式,与Python端默认行为对齐:

import * as crypto from 'crypto';

const encryptMessage = (serverPublicKey: string, message: string): string => {
  const encryptedBuffer = crypto.publicEncrypt(
    {
      key: serverPublicKey,
      padding: crypto.constants.RSA_PKCS1_PADDING // 指定PKCS#1 v1.5填充
    },
    Buffer.from(message, 'utf-8')
  );
  return encryptedBuffer.toString('base64');
};

方案2:统一使用OAEP填充(修改Python解密代码)

若希望保留Node.js默认的OAEP填充,修改Python代码适配该填充方式:

import rsa
import base64
from rsa.pkcs1 import OAEP

# 加载PKCS#1格式的私钥
with open('server_private_key.pem', 'r') as f:
    private_key = rsa.PrivateKey.load_pkcs1(f.read())

def decrypt_message(encrypted_data: str) -> str:
    encrypted_bytes = base64.b64decode(encrypted_data)
    # 使用OAEP填充解密,与Node.js默认配置对齐
    decrypted_bytes = rsa.decrypt(encrypted_bytes, private_key, padding=OAEP)
    return decrypted_bytes.decode('utf-8')

额外注意事项

  • 密钥格式验证:确保私钥为PKCS#1格式(以-----BEGIN RSA PRIVATE KEY-----开头),Python端通过rsa.PrivateKey.load_pkcs1正确加载;Node.js crypto 原生支持PKCS#1格式公钥。
  • 消息长度限制:RSA单条加密消息长度有限(2048位密钥下,PKCS#1 v1.5最多加密245字节,OAEP最多214字节),若消息过长,建议采用「对称加密(如AES)加密消息 + RSA加密对称密钥」的混合方案。
  • 哈希算法同步:若使用OAEP填充,需确保两端哈希算法一致(Node.js默认SHA-1,Python OAEP 类默认也是SHA-1,如需修改需同步两端配置)。

内容的提问来源于stack exchange,提问作者GentalTM

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 14:23:13