Search code examples
node.jsazure-storage

Azure storage Node.js SDK - MD5 hash not the same as local


I did read the other threads in SO, but none was helpful.

blobService.getBlobProperties("qauploads", "brand.gif", function(err, properties, status) {

  let buff = new Buffer(properties.contentSettings.contentMD5);
  let base64data = buff.toString('base64');
  console.log("remote " + base64data)
})

  fileHash('md5', "temp/brand.gif").then(res => {
      console.log("local "+ res)
  })



function fileHash(algorithm, path) {
  return new Promise((resolve, reject) => {
    // Algorithm depends on availability of OpenSSL on platform
    // Another algorithms: 'sha1', 'md5', 'sha256', 'sha512' ...
    let shasum = crypto.createHash(algorithm);
    try {
      let s = fs.ReadStream(path)
      s.on('data', function (data) {
        shasum.update(data)
      })
      // making digest
      s.on('end', function () {
        const hash = shasum.digest('hex')
        return resolve(hash);
      })
    } catch (error) {
      return reject('calc fail');
    }
  });
}

The output:

local 8112398e797d24a66e66d149c4962733
remote Z1JJNWpubDlKS1p1WnRGSnhKWW5Ndz09

But they are the same exact file! When I download it manually and check its hash, it's the same as local.

I dunno what's wrong.


Solution

  • Please try this code:

    function fileHash(algorithm, path) {
      return new Promise((resolve, reject) => {
        // Algorithm depends on availability of OpenSSL on platform
        // Another algorithms: 'sha1', 'md5', 'sha256', 'sha512' ...
        try {
          const input = fs.createReadStream(path);
          const output = crypto.createHash(algorithm);
    
          output.once('readable', () => {
            const md5 = output.read().toString('base64');
            resolve(md5);
          });
    
          input.pipe(output);
        } catch (error) {
          return reject('calc fail');
        }
      });
    }
    

    I tested it against a blob in my storage account and both matched.