title: How do I decrypt a file using node-rsa with public and private keys?
body: <p>I was following this tutorial on <a href="https://medium.com/@ian.mundy/writing-a-node-js-script-4baef96104da" rel="nofollow noreferrer">medium</a>.  However the tutorial does not explain how to decrypt the encrypted file.  Nor does it explain how the public / private keys are used.</p>
  
  <p>Simply running decrypt does not work with the error below.</p>
  
  <p><a href="https://i.stack.imgur.com/e51ew.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e51ew.png" alt="enter image description here"></a></p>
  
  <p>Relevant documentation appears to be on <a href="https://www.npmjs.com/package/node-rsa#encryptingdecrypting" rel="nofollow noreferrer">npmjs.com</a>.</p>
  
  <p><strong>Actual Code</strong></p>
  
  <pre><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?
  </code></pre>
  
  <p><strong>default.txt</strong></p>
  
  <p>test</p>
  
  <p><strong>encrypted.txt</strong></p>
  
  <blockquote>
    <p>qLs0dUez+LzhlNBGnvEzLRdYF0HUHoRignMxT2MZO7Qs8tMvkmWbiA1oxJbT7ZC5bPS+dHvFgbiWbdje/3/Y17JT8JxflryJU6394UPfsTDLmtZZroemTtTzJxVnGZlw0IyQtfn79eysQaEoKMQ9hKjDySxO1gLwJJZ1DoxW7CNu0BqfcGUMcREQ+ozrhKpMRK0piWUWqHYwX0EIxQT8/rh5ER+tCdh4lR7N5+FPA4VOde3z/36DvQ9KOMChS7m91aH0QXUqhMaHtjslvcoj4i1Rwzd0qn1imHPc8LncZz6hv2deRqU65rS+M6UeC9LWJjblVf2er25x8B1yszaV+A==</p>
  </blockquote>