CryptoJS consistently produces identical hash values for distinct files

Utilizing CryptoJS to generate a hash value for uploaded files has presented me with a challenge. Despite my efforts, all files I upload seem to produce identical hash values. It appears that the issue lies within my "onFileChange" function, but pinpointing the mistake is proving to be elusive. Any assistance in resolving this matter would be greatly appreciated.

import React, { Component } from 'react'; 
import { connect } from 'react-redux';
import '../CSS/FileSelectorCSS.css';
var CryptoJS = require("crypto-js");

class FileSelectorComponent extends Component {

    state = {

        // Initially, no file is selected 
        selectedFile: null
    };

    // On file select (from the pop up) 
    onFileChange = event => {
        var text = '';
        // Update the state 
        this.setState({ selectedFile: event.target.files[0] });

        var reader = new FileReader();

        reader.onloadend = function () {
            text = (reader.result);
        }

        reader.readAsBinaryString(event.target.files[0]);

        var hash = CryptoJS.MD5(CryptoJS.enc.Latin1.parse(text));

        console.log(hash.toString());
    };

    // Display file details after upload 
    fileData = () => {

        if (this.state.selectedFile) {

            return (
                <div>
                    <h2>File Details:</h2>
                    <p>File Name: {this.state.selectedFile.name}</p>
                    <p>File Type: {this.state.selectedFile.type}</p>
                    <p>
                        Last Modified:{" "}
                        {this.state.selectedFile.lastModifiedDate.toDateString()}
                    </p>
                </div>
            );
        } 
    };

    render() {

        return (
            <div>
                <div>
                    <input type="file" onChange={this.onFileChange} />
                </div>
                {this.fileData()}
            </div>
        );
    }
} 

export default connect()(FileSelectorComponent);

https://i.sstatic.net/Y75Ju.png

Expected result: https://i.sstatic.net/314WZ.png

Answer №1

Calculating the hash before the reader is fully loaded can lead to errors.

The MD5 hash "d41d8cd98f00b204e9800998ecf8427e" represents an empty string.

These lines indicate:

reader.onloadend = function () {
  text = (reader.result);
}

the text variable will receive the result after the reader has finished loading asynchronously. However, at that point, the rest of the function has already executed.

To ensure that the process occurs after the text variable is updated, modify it like this:

reader.onloadend = function () {
  text = (reader.result);

  reader.readAsBinaryString(event.target.files[0]);
  var hash = CryptoJS.MD5(CryptoJS.enc.Latin1.parse(text));
  console.log(hash.toString());
}

Answer №2

  // When a file is selected (from the popup) 
onFileChange = event => {
    var text = '';
    // Update the state with the selected file 
    this.setState({ selectedFile: event.target.files[0] });
    console.log(event.target.files[0]);
    var reader = new FileReader();

    reader.onloadend = function () {
        text = (reader.result);
        var hash = CryptoJS.MD5(CryptoJS.enc.Latin1.parse(text));
        console.log(hash.toString());
    }

    reader.readAsBinaryString(event.target.files[0]);

    //console.log(text);
   

    //console.log(hash.toString());
};

To fix my issue, I had to place CryptoJS inside the callback function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Pug: perform a task depending on the presence of an element within a variable

I'm currently working with Express js to create a web application. I make use of an API to fetch some data, which is then sent to a pug file in the following format. res.render('native.pug', {product_name: body.products, cart_items:body.car ...

The Bootstrap form validation is preventing the Ajax request from functioning properly

Having successfully implemented a form with Bootstrap validation, I encountered an issue where the AJAX Post method fails to execute after validation. The catch clause does not capture any errors and only the ajax portion of the code doesn't run. Belo ...

Oops! We couldn't locate or access the file you're trying to import: ~bootstrap/scss/bootstrap

Following the steps outlined on getbootstrap.com, I assumed that everything would function smoothly. Unfortunately, that hasn't been the case so far. All seems well until I attempt to load the page, at which point my Express.js app throws a: [[ ...

Challenges faced with react-bootstrap-autosuggest

After spending the entire day attempting to integrate the package from here into my create-react-app project upon ejection, I encountered the following error: Failed to compile. Error in ./~/react-bootstrap-autosuggest/lib/Autosuggest.js Module not found ...

What is the process for converting this Greasemonkey code to JavaScript specifically for Android devices?

Having trouble loading a page and running a JavaScript code on it? Don't worry, you're not alone. I came across a Greasemonkey script that does the trick, but now I'm struggling to make it work on Android. It's probably because of my la ...

I am having trouble with an undefined variable in my expressjs server.js file. How can I properly reference

When setting up ExpressJS, I have a file named server.js where the following code is executed: import { call_method } from '../hereIam.mjs'; const process_db = async () => { console.log(this); // undefined call_method(this); }; console. ...

What is causing the issue with updating the user in MongoDB using this code?

Currently, I am working on fetching a team's schedule from an excel file and then adding those shifts to the user's shifts in MongoDB. I have tried adding them to an object first and then to the user's shifts field, but nothing seems to be h ...

Attempting to control an array of objects

In my current records: The parts with IDs 14.3, 14.2, and 14.1 belong to part ID = 30. The goal is to achieve the following: 1) By default, the first two IDs will be selected. If a user tries to select ID = 71, which belongs to part 30, they should not ...

I'm curious about the potential vulnerabilities that could arise from using a Secret key as configuration in an express-session

Our code involves passing an object with a secret key's value directly in the following manner --> app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: { secure: true } }) I am pondering wheth ...

tips for personalizing your jQuery image preview script

Currently, I have implemented a jQuery script that allows me to preview multiple images before uploading them. Although the functionality works well, I am facing difficulties customizing it to meet my specific requirements. <script> $(document).r ...

Real-time data and dynamic checkbox functionality in AngularJS

I am working on an onclick function that involves data stored in objects. $scope.messages = [ {"id": "1"}, {"id": "2"}, {"id": "3"}, {"id": "4"}, ]; $scope.selection = { ids: {} }; $scope.sendMe = function(message) { //send the data with `id` and ...

Error parsing data in the $.ajaxSetup() function of JQuery

Currently, I am coding a program using jQuery. It was functioning perfectly in Firefox 3.5 until I upgraded to Firefox 4.0. Since then, the dreaded 'parsererror' keeps popping up and causing me quite a headache. I've pinpointed the exact pa ...

URL JSON data will not display markers

I am currently working on a map that fetches data from the police.uk API by allowing users to drag and drop a dot on the map to display crimes within a 1-mile radius. However, I'm facing an issue when trying to implement geocoding functionality by tak ...

Is there a term similar to "Rise above the Rest" in the world of Web Development?

Hey, I've encountered a new issue right now. Currently, I have two elements that are fixed to the top and bottom of the page. However, the elements in between them are overlapping the top element. Even though I tried keeping both elements fixed, th ...

Unable to integrate an if/else statement into the JSON reply

Working with an API to retrieve data and display images from it. I am attempting to implement an if/else statement that will show photos if the search term yields results in the response, and display a message indicating no results if it does not. Curren ...

Issues with Angular route links not functioning correctly when using an Array of objects

After hard coding some routerLinks into my application and witnessing smooth functionality, I decided to explore a different approach: View: <ul class="list navbar-nav"></ul> Ts.file public links = [ { name: "Home&quo ...

Tips on displaying a message when search results are not found

import React, { useState, useEffect } from 'react' import axios from 'axios' function DataApi({ searchTerm }) { const [users, setUsers] = useState([]) const [loading, setLoading] = useState(false) const [error, setError] = useSta ...

Display the size of the data array in VueJS once the data has been retrieved from the API

Using Vue JS, I have been attempting to retrieve data from an API. My goal is to determine the length of the array and then log it to the console using a method. However, every time I try to do this, the value logged is always "0" instead of the actual le ...

Navigating poorly structured HTML tables using jQuery code loops

I am currently working on a project that involves an HTML table generated by my client, and it seems like we are both in agreement not to change how the code is generated at this time. <TABLE BORDER=0 CELLSPACING=0 CELLPADDING=0> <TR HEIG ...

Recognizing mouse and keyboard inputs within an Angular application when using ng-repeat

In my application, I am dynamically generating a series of spans using ng-repeat, with each span having a unique id (e.g. span-{{$index}}). Now, I am looking to implement the following functionality: When clicking on a span, I want to copy the id of that ...