0

I am using keccak256 npm module to calculate the hash of an uploaded file. I verify the correctness and I see that the given hash does not correspond to the ones compared on some online hash calculators (such as: this or this or this ).

The code I run is:

const express = require('express');
const fs = require('fs');
const keccak256 = require('keccak256');
const formidable = require('formidable'),
    http = require('http'),
    util = require('util');

const router = express.Router();

router.get('/', (req, res) => {
  res.sendFile('index.html', {root: __dirname })
});


router.post('/upload', (req, res) => {
  var form = new formidable.IncomingForm();

    form.parse(req, function(err, fields, files) {
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload saved in: ' + files.upload.path + '\n\n');
      var readStream = fs.createReadStream(files.upload.path);
      //res.write(readStream);
      console.log(keccak256(readStream).toString('hex'))
      res.end("");

    });

    return;
});

Can anyone kindly explain to me where I am wrong and how I can correct it?

shogitai
  • 1,823
  • 1
  • 23
  • 50
  • 1
    Something to do with using `'hello'` instead of the contents of the file? – Ry- Feb 14 '19 at 07:51
  • I corrected, but I get `/node_modules/keccak256/dist/index.js:34 throw new Error('invalid type'); Error: invalid type at toBuffer`. – shogitai Feb 14 '19 at 08:17

1 Answers1

0

Solved by using NPM sha-3:

const express = require('express');
const fs = require('fs');
const formidable = require('formidable'),
    http = require('http'),
    util = require('util');
const { Keccak } = require('sha3');
const hash = new Keccak(256);

const router = express.Router();

router.get('/', (req, res) => {
  res.sendFile('index.html', {root: __dirname })
});


router.post('/upload', (req, res) => {
  var form = new formidable.IncomingForm();

    form.parse(req, function(err, fields, files) {
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload saved in: ' + files.upload.path + '\n\n');
      var file = fs.readFileSync(files.upload.path);
      hash.update(file);
      console.log(hash.digest('hex'));
      res.end("");

    });

    return;
});

Now it works fine.

shogitai
  • 1,823
  • 1
  • 23
  • 50