I was following this tutorial on medium. However the tutorial does not explain how to decrypt the encrypted file. Nor does it explain how the public / private keys are used.
Simply running decrypt does not work with the error below.
Relevant documentation appears to be on npmjs.com.
Actual Code
// node modules
const fs = require('fs');
// npm modules
const parseArgs = require('minimist');
const NodeRSA = require('node-rsa');
// get command line arguments
const argv = parseArgs(process.argv.slice(2));
// console.dir(argv);
// read a file
const file = fs.readFileSync('' + argv.file, 'utf8');
// generate keys
const key = new NodeRSA().generateKeyPair();
const publicKey = key.exportKey('pkcs8-public-pem');
const privateKey = key.exportKey('pkcs1-pem');
// write public key
fs.openSync('keys/public.pem', 'w');
fs.writeFileSync('keys/public.pem', publicKey, 'utf8');
// write private key
fs.openSync('keys/private.pem', 'w');
fs.writeFileSync('keys/private.pem', privateKey, 'utf8');
// write encrypted file
const encrypted = key.encrypt(file, 'base64');
fs.openSync('encrypted.txt', 'w');
fs.writeFileSync('encrypted.txt', encrypted, 'utf8');
// read encrypted file
const fileEncrypted = fs.readFileSync('encrypted.txt', 'utf8');
const decrypted = key.decrypt(fileEncrypted, 'base64'); // error here
// has to do with key generation?
default.txt
test
encrypted.txt
qLs0dUez+LzhlNBGnvEzLRdYF0HUHoRignMxT2MZO7Qs8tMvkmWbiA1oxJbT7ZC5bPS+dHvFgbiWbdje/3/Y17JT8JxflryJU6394UPfsTDLmtZZroemTtTzJxVnGZlw0IyQtfn79eysQaEoKMQ9hKjDySxO1gLwJJZ1DoxW7CNu0BqfcGUMcREQ+ozrhKpMRK0piWUWqHYwX0EIxQT8/rh5ER+tCdh4lR7N5+FPA4VOde3z/36DvQ9KOMChS7m91aH0QXUqhMaHtjslvcoj4i1Rwzd0qn1imHPc8LncZz6hv2deRqU65rS+M6UeC9LWJjblVf2er25x8B1yszaV+A==