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

如何在低版本Node.js中解密Python PKCS1-OAEP加密数据

Solution for Decrypting Python PKCS1-OAEP Encrypted Data in Old Node.js Versions

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-forge is 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:13:07