electron - how to generate file checksum

Viewed 905

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?

2 Answers

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));

If the file contents are already in memory:

const checksum = crypto.createHash('sha256').update(contents).digest('base64')
Related