Search code examples
node.jshashmulter

NodeJS Express Upload - Setting and Comparing MD5 Hash codes


I have a React user interface with a NodeJS express backend, through which users can upload files. To prevent tampering, I would like to generate a hash code for the file contents prior to the file upload, send that with the file to the express upload route, compute a hash code for the uploaded contents and then compare the two hash codes to ensure that the file contents are the same (within the limits of hash code uniqueness).

I'm able generate an MD5 hash code on the contents in the React UI and send that along with the file to the back end. But I can't figure out how to take the uploaded file contents and create a hash code for that.

I'm using Multer and tried Multer-MD5 as well as writing my own using CryptoJS. I suspect the issue lies in trying to convert the uploaded content (which seems to be a buffer) into something CryptoJS can process.

Or use another Hash generator.

Has anyone had to work through this before?


Solution

  • I worked out a solution, partly because I expect the uploaded content to be text.:

    utils.fileHash(file.buffer.toString())
    
    and 
    
    fileHash: (file) => {
        return CryptoJS.MD5(file).toString();
    },