'What is the equivalent of this php code in Nodejs?

I have this php code to encrypt and decrypt with RSA, I use only the encrypt data, because I need to decrypt the data with Node.js

<?php
include 'vendor/autoload.php';

use phpseclib3\Crypt\PublicKeyLoader;

function rsaEncryptionOaepSha256($publicKey, $plaintext) {
    $rsa = PublicKeyLoader::load($publicKey)
        ->withHash('sha256')
        ->withMGFHash('sha256');
    return $rsa->encrypt($plaintext);
}

function rsaDecryptionOaepSha256($privateKey, $ciphertext) {
    $rsa = PublicKeyLoader::load($privateKey)
        ->withHash('sha256')
        ->withMGFHash('sha256');
    return $rsa->decrypt($ciphertext);
}

My Node.js code is the following, but doesn't work


const NodeRSA = require('node-rsa');

decryptRsaWithPrivateKey(encrypted: string): string {
  const rsaKey = new NodeRSA(process.env.RSA_PRIVATE_KEY);
  rsaKey.setOptions({ encryptionScheme: 'pkcs1' });
  return rsaKey.decrypt(encrypted, 'utf8');
}

I get the following error:

Error during decryption (probably incorrect key). Original error: Error: error:0407109F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error at NodeRSA.module.exports.NodeRSA.$$decryptKey

I already tried with other configurations but is still fails

Thanks in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source