如何在低版本Node.js中解密Python PKCS1-OAEP加密数据
Since your Node.js version lacks the crypto.privateDecrypt() function and you can't upgrade right now, the best approach is to use a lightweight, compatible third-party library called node-forge—it fully supports PKCS1-OAEP decryption and works with most older Node.js releases.
Step 1: Install node-forge
First, add the library to your project via npm:
npm install node-forge
Step 2: Write the Decryption Code
Make sure to match the hash algorithm used in your Python encryption code (this is critical for successful decryption). Below are examples for both common scenarios:
Example 1: If Python used SHA-256 for PKCS1-OAEP
Here's what your Python encryption might look like (for reference):
from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP import hashlib # Load public key public_key = RSA.import_key(open("public.pem").read()) # Initialize cipher with SHA-256 cipher = PKCS1_OAEP.new(public_key, hashAlgo=hashlib.sha256) # Encrypt data encrypted_data = cipher.encrypt(b"your sensitive message")
Corresponding Node.js decryption code:
const forge = require('node-forge'); const fs = require('fs'); // Load your PEM-formatted private key const privateKeyPem = fs.readFileSync('./private.pem', 'utf8'); const privateKey = forge.pki.privateKeyFromPem(privateKeyPem); // Assume `encryptedData` is the Buffer/bytes you received from Python const encryptedBuffer = forge.util.createBuffer(encryptedData); // Decrypt using PKCS1-OAEP with SHA-256 (match Python's hash) const decryptedBuffer = privateKey.decrypt(encryptedBuffer, 'RSA-OAEP', { md: forge.md.sha256.create(), mgf1: { md: forge.md.sha256.create() } }); // Convert decrypted bytes back to string const decryptedText = decryptedBuffer.toString(); console.log('Decrypted content:', decryptedText);
Example 2: If Python used the default SHA-1 for PKCS1-OAEP
If your Python code didn't specify a hash algorithm (defaults to SHA-1), adjust the Node.js code to use SHA-1 instead:
const decryptedBuffer = privateKey.decrypt(encryptedBuffer, 'RSA-OAEP', { md: forge.md.sha1.create(), mgf1: { md: forge.md.sha1.create() } });
Key Notes
- Ensure your private key is in valid PEM format (no missing headers/footers, no extra whitespace).
- Double-check that the hash algorithm in Node.js exactly matches what was used in Python—mismatches will cause decryption failures.
node-forgeis widely maintained and compatible with Node.js versions as far back as v4, so it should work for your constrained environment.
内容的提问来源于stack exchange,提问作者Neetu Soni

