electron – how to generate file checksum

Issue

I have an electron app that will generate encrypted files. I want to provide to the user the checksum of the encrypted files to give the user the ability to check if the files aren’t modified. How I can achive this with electron and node js api?

Solution

Node.js has the inbuilt crypto library with a variety of different crypto algorothims

const crypto = require('crypto');
function getChecksum(path) {
    return new Promise((resolve, reject) => {
      // if absolutely necessary, use md5
      const hash = crypto.createHash('sha256');
      const input = fs.createReadStream(path);
      input.on('error', reject);
      input.on('data', (chunk) => {
          hash.update(chunk);
      });
      input.on('close', () => {
          resolve(hash.digest('hex'));
      });
    });
}

Example usage:

getChecksum('someFile.txt')
.then(checksum => console.log(`checksum is ${checksum}`))
.catch(err => console.log(err));

Answered By – t348575

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.