Nodejs implements RSA private key decryption

Need

Use node.js to implement RSA private key decryption, known

  1. Padding method: PKCS1_PADDING

  2. Output type: hex

  3. Character set: utf8 encoding

  4. Private key:

    -----BEGIN PRIVATE KEY-----
    XXXXXXXXXXXX
    -----END PRIVATE KEY-----
  5. Text to be decrypted: YYYYYYYYYYYYYYYY

Please get the decryption conversion result

Code

To implement RSA private key decryption using Node.js, you can use Node.js crypto module and privateDecrypt method to do it. Here is a sample code for decryption with given parameters:

For security, we put the private key text in the key.pem file in the same directory as the script, and then write the following script.

const crypto = require('crypto');

// text to be decrypted
const encryptedText = 'YYYYYYYYYYYYYY';

// decryption function
function decryptRSA(encryptedText) {
    try {
        const buffer = Buffer.from(encryptedText, 'hex');

        const decrypted = crypto.privateDecrypt(
            {
                key: fs.readFileSync(path.join(__dirname, '/key.pem'), 'utf8'),
                padding: crypto.constants.RSA_PKCS1_PADDING
            },
            buffer
        );
        return decrypted.toString('utf8');
    } catch (error) {
        console.log('License decrypt error')
        return null
    }

}

// perform decryption
const decryptedText = decryptRSA(encryptedText);
console.log(decryptedText);

The above code will print out the decrypted text. Note that the private key should be provided to the code in the correct format (Base64 encoded), and make sure your Node.js version supports RSA private key decryption.

Reference

Comments