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

Node.js RSA非对称加密后Python解密报错:Ciphertext length must be equal to key size

Node.js RSA加密与Python解密跨语言兼容问题解决

Hey there, let's fix that frustrating ValueError: Ciphertext length must be equal to key size error you're hitting when trying to decrypt Node.js-encrypted data in Python. You were right to suspect padding mismatches, but there's another small (but critical) step you missed with how the ciphertext is handled between the two languages. Let's walk through the solution step by step.

What's Going Wrong?

Your setup is almost there: you generated a valid 4096-bit RSA key pair, used RSA_PKCS1_OAEP_PADDING with SHA256 in Node.js for encryption, and tried matching those settings in Python. The problem? You converted the encrypted binary data to Base64 in Node.js, but forgot to convert it back to raw bytes in Python before decrypting. Plus, we need to make 100% sure all OAEP parameters are identical across both languages.

Fixed Code Snippets

1. Node.js Encryption (Minor Tweaks)

Your existing code is mostly solid—we just add explicit encoding to avoid any hidden issues:

const crypto = require("crypto");
const fs = require("fs");

// Load the public key
const publicKey = fs.readFileSync('./public_key.pem', 'utf8');
// Text to encrypt
const plainText = "123456";

// Perform encryption with OAEP padding and SHA256
const encryptedBuffer = crypto.publicEncrypt(
    {
        key: publicKey,
        padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
        oaepHash: 'sha256'
    },
    Buffer.from(plainText, 'utf8') // Explicit UTF-8 encoding
);

// Convert to Base64 for easy transport/storage
const encryptedBase64 = encryptedBuffer.toString('base64');
console.log("Encrypted Base64:", encryptedBase64);

2. Python Decryption (Key Fixes)

Here's where we address the Base64 decoding and ensure full parameter alignment with Node.js:

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
import base64

# Replace this with the Base64 string output from your Node.js code
encrypted_base64 = "INSERT_YOUR_NODEJS_ENCRYPTED_BASE64_HERE"

# Convert Base64 back to raw binary bytes (this was the missing step!)
encrypted_bytes = base64.b64decode(encrypted_base64)

# Load the private key (matching the public key used in Node.js)
with open("./private_key.pem", "rb") as key_file:
    private_key = serialization.load_pem_private_key(
        key_file.read(),
        password=None,
    )

# Decrypt with identical OAEP settings to Node.js
original_message = private_key.decrypt(
    encrypted_bytes,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

# Convert bytes back to UTF-8 string
print("Decrypted message:", original_message.decode('utf8'))

Quick Checks to Avoid Future Issues

  • Use matching key pairs: Double-check that the public key in Node.js and private key in Python are from the same OpenSSL-generated pair—mixing keys will always cause failures.
  • Stick to UTF-8: Consistently use UTF-8 when converting between strings and bytes in both languages to avoid encoding mismatches.
  • Parameter parity: Always mirror padding, hash algorithms, and OAEP settings exactly across languages—even a tiny mismatch (like using SHA1 instead of SHA256) will break things.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 12:42:45