const crypto = require('crypto');

class RSAAESEncryption {
    static generateRSAKeyPair(keySize) {
        return new Promise((resolve, reject) => {
            crypto.generateKeyPair('rsa', {
                modulusLength: keySize,
                publicKeyEncoding: { type: 'spki', format: 'pem' },
                privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
            }, (err, publicKey, privateKey) => {
                if (err) {
                    reject(err);
                } else {
                    resolve({ publicKey, privateKey });
                }
            });
        });
    }

    static encryptLargeDataWithRSA(data, publicKeyPEM) {
        const publicKey = crypto.createPublicKey(publicKeyPEM);
        const aesKey = crypto.randomBytes(32); // 256 bits for AES-256

        const encryptedAESKey = crypto.publicEncrypt({
            key: publicKey,
            padding: crypto.constants.RSA_PKCS1_OAEP_PADDING
        }, aesKey);

        const iv = crypto.randomBytes(16); // Initialization Vector for AES
        const cipher = crypto.createCipheriv('aes-256-cbc', aesKey, iv);

        const encryptedData = Buffer.concat([iv, cipher.update(data), cipher.final()]);

        return Buffer.concat([encryptedAESKey, encryptedData]);
    }

    static decryptLargeDataWithRSA(encryptedData, privateKeyPEM) {
        const privateKey = crypto.createPrivateKey(privateKeyPEM);
        const encryptedAESKey = encryptedData.slice(0, 16);
        const encryptedDataOnly = encryptedData.slice(16);
        console.log(encryptedAESKey)

        const aesKey = crypto.privateDecrypt({
            key: privateKey,
            padding: crypto.constants.RSA_PKCS1_OAEP_PADDING
        }, encryptedAESKey);

        const iv = encryptedDataOnly.slice(0, 16);
        const ciphertext = encryptedDataOnly.slice(16);

        const decipher = crypto.createDecipheriv('aes-256-cbc', aesKey, iv);

        return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
    }
}

const privateKeyPEM = `
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDPtNZz3MCyxGGE5yWqq6r8BUAWIUhHH7UNJ4mrfzOpc9ojRxcNkqq1mgyGetoFHgRWYbU6z/Me1yO5ucgV9FaYU1PnPtX4XlJifor+BzdnzDjCB4VXNFR00brcmrsflDd21aCJlqEpRJhn4d03mm1CspcVDNnEQp4ETBkr0+wymQIDAQABAoGAAYJxmBV5cRq+WjkDXbZtIfnzNpbNkkrdIog4pgo1HPpwc+fJ5rHkOgM02rPuof73k3HuekvT18nQTpBCcvIVLDrObui+HzrUlaZ8AAmhdIYlEkp9pwq4FuShc0EIfGN4GM/nYo9GZBsmvr6ndBAhlQwmxnn+ZAxnsIRuialCB7UCQQDqLPtk41K7i547OPmelbjuFAglKCRf74i5Cik0BkzDwOHauFO0k4Fy7/cKftCChQNGjooryl2Fz3hAaWcLANE1AkEA4xBYP6evLF0CBW4Yb+Qu2IiW2CIH1k+W3c0HlNBySpHFbhpy0H3ht02CDyqlaLRrfxwkF13kZ2PviIN0eL9MVQJBAM7WWF4uI38fvO0WT/Twzd0LuH4JTMen7R1zih03i0pD7bmgod6XgvkgVxXgGQ+PqOsDL6uqHJz6OX67GpavbBkCQQDTJ3L5lyVmuwNTK2PcQbVyteqZCWSCXrcsgisnr4RpZg/UaRIWYsnRnWlyUzVJHmbM6M2DUVRC9YNeTui0FSmVAkAzhKth6fPxOAELHVSf3xf98PXKcAvch52uIm+/2oNGNpJLjd/EpU8vn+x7PoZH0SU4Ll5l27MQw+ulRB3EWolh
-----END RSA PRIVATE KEY-----
`

const encryptedData = Buffer.from("eVEOnrU86BNgEzXE9tMKWJxbjEHRNLTrtH/6uv6+YDekUo+hjBCTY/pnKpgn1AmG4dH5+gQKbEmtZKtT/m584siNefANMhwjIAOIZLo07mqDy8EyY6Rt52xdY0Uy7qq0aTN42vbXbPdAadWyohh7OuhimyDc7J8WP4c+g5h1VlLOUnvzGYdw0KpPnXodvhWVfwY4M607b1pACrnjoAHsPg==", 'base64') 
const decryptedData = RSAAESEncryption.decryptLargeDataWithRSA(encryptedData, privateKeyPEM);
console.log(decryptedData)

// Example usage
// (async () => {
//     try {
//         const keySize = 1024; // Choose an appropriate key size
//         const { publicKey, privateKey } = await RSAAESEncryption.generateRSAKeyPair(keySize);

//         const plaintext = 'Hello, RSA and AES encryption in JavaScript!';
//         const encryptedData = RSAAESEncryption.encryptLargeDataWithRSA(Buffer.from(plaintext), publicKey);

//         console.log('Encrypted Data:', encryptedData.toString('base64'));

//         const decryptedData = RSAAESEncryption.decryptLargeDataWithRSA(encryptedData, privateKey);
//         console.log('Decrypted Data:', decryptedData.toString('utf8'));
//     } catch (error) {
//         console.error('Error:', error);
//     }
// })(); 
by

NodeJS Online Compiler

Write, Run & Share NodeJS code online using OneCompiler's NodeJS online compiler for free. It's one of the robust, feature-rich online compilers for NodeJS language,running on the latest LTS version NodeJS 16.14.2. Getting started with the OneCompiler's NodeJS editor is easy and fast. The editor shows sample boilerplate code when you choose language as NodeJS and start coding. You can provide the dependencies in package.json.

About NodeJS

Node.js is a free and open-source server environment. Node.js is very popular in recent times and a large number of companies like Microsoft, Paypal, Uber, Yahoo, General Electric and many others are using Node.js.

Key features

  • Built on Google chrome's javascript engine V8 and is pretty fast.
  • Node.js was developed by Ryan Dahl in 2009.
  • Server-side platform for building fast and scalable applications.
  • Node.js is Asynchronous, event-driven and works on single-thread model thus eliminating the dis-advantages of multi-thread model.
  • Supports various platforms like Windows, Linux, MacOS etc.
  • Provides rich library of java script modules which simplifies the development efforts.
  • Released under MIT license.

Express Framework

Express is one of the most popular web application framework in the NodeJS echosystem.

  • Pretty fast
  • Minimalist
  • Unopinionated
  • Very flexible

Syntax help

Examples

Using Moment

let moment = require('moment');

console.log(moment().format('MMMM Do YYYY, h:mm:ss a'));

Using Lodash

const _ = require("lodash");

let colors = ['blue', 'green', 'yellow', 'red'];

let firstElement = _.first(colors);
let lastElement = _.last(colors);

console.log(`First element: ${firstElement}`);
console.log(`Last element: ${lastElement}`);

Libraries supported

Following are the libraries supported by OneCompiler's NodeJS compiler.

  • lodash
  • moment
  • underscore
  • uuid
  • ejs
  • md5
  • url