title: Encrypting a file with Nodejs (Crypto) throw an error: bad base64 decode
body: <p>Hello and sorry if my question is stupid, I'm just beginning on nodejs and bring a heavy luggage from PHP world.</p>
  
  <p>I'm trying to encrypt a file using a public key generated through linux command line using the GnuPG command.</p>
  
  <p>On my app I use Express, fs and Crypto to create a buffer from the file and get the public key content and then use publicEncrypt to get the encrypted data.</p>
  
  <p>When I do so the application stops and throw an error complaining about the PEM format: bad base64 decode.</p>
  
  <pre><code>Error: error:0906D064:PEM routines:PEM_read_bio:bad base64 decode
  </code></pre>
  
  <p>Here you have the main parts of this code:</p>
  
  <pre><code>var encryptStringWithRsaPublicKey = function(toEncrypt, relativeOrAbsolutePathToPublicKey) {
  var absolutePath = path.resolve(relativeOrAbsolutePathToPublicKey);
  var publicKey = fs.readFileSync(absolutePath, "utf8");
  if(typeof toEncrypt !=='object') return false;
  var buffer = new Buffer(toEncrypt);
  console.log(publicKey);
  var encrypted = crypto.publicEncrypt(publicKey, buffer);
  return encrypted.toString("base64");
  </code></pre>
  
  <p>};</p>
  
  <pre><code>        fs.readFile(req.files[0].path, function (err, data){
              var encrypted = encryptStringWithRsaPublicKey(data, '/home/app/data/pub_key.txt');
              if(!encrypted) {
                  fs.writeFile("/home/app/data/uploads/enc1/test.pdf", encrypted, function(err) {
                      if(err) {
                          return console.log(err);
                      }
  
                      console.log("The file was saved!");
                      res.end(req.files[0].filename);
                  }); 
              }
              else {
                  res.end({error:'encryption failed. all data deleted.'});
              }
          });
  </code></pre>
  
  <p>Maybe the Public Key has some end of line bad characters somewhere or maybe Crypto requires a very special format?</p>
  
  <p>This is the content of the pub key:</p>
  
  <pre><code>-----BEGIN PGP PUBLIC KEY BLOCK-----
  Version: GnuPG v1
  
  mQENBFiFz2ABCADGk6E2IgbaGYIHO7EVNotxiDjB4k5UZJ4xx41RwY9LeG0c+SLW
  rC/ijPFJZ/kN3nrpvTAZEYpnK51olqvw/OOgt5p3k32mW47HALx91vU9WRrykt2Y
  DMj+aeMDi5QZnda8qTn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