Angularjs application and bash script generating different SHA256 hashes for the same file

In my AngularJS app, I am struggling to get the digest of an uploaded file. The issue is that the resulting hash is not matching the one obtained using bash locally.

Initially, I used jshashes, but when I noticed discrepancies in the hashes generated by the web app and bash, I switched to CryptoJS. However, even with CryptoJS, the hash for the uploaded file remains inconsistent.

Here's a snippet of the code I'm working with:

var reader = new FileReader();    
reader.readAsBinaryString(controller.file);
controller.fileHash = CryptoJS.SHA256(reader.result).toString(CryptoJS.enc.Hex);

The above code essentially reads the uploaded file using FileReader, converts it into a BinaryString, computes the hash, and then displays the result in the html through another controller variable.

On my local shell environment, I use the following command to calculate the file digest:

$ shasum -a 256 [path/to/file]

I am utilizing ng-file-upload for file uploads.

If anyone can offer assistance or point me towards a solution, I would greatly appreciate it.

Thank you for your help.

Update 1: As per @destroyer's comment, I have modified the code to incorporate the asynchronous nature of readAsBinaryString:

var reader = new FileReader();
reader.onload = function() {
    controller.fileHash = CryptoJS.SHA256(reader.result).toString(CryptoJS.enc.Hex);
};
reader.readAsArrayBuffer(controller.file);

I attempted a solution mentioned here to convert the ArrayBuffer object into a BinaryString, but the issue persists.

Update 2: I have included a console log image of the object I am attempting to hash https://i.sstatic.net/2Y0zD.png

Answer №1

readAsBinaryString is no longer recommended; instead, consider using readAsArrayBuffer.

In any case, both functions initiate an asynchronous task, the outcome of which can be accessed in the load event of the FileReader instance.

var reader = new FileReader();    
reader.onload = function(){
  controller.fileHash = CustomSHA256(reader.result).toString(CustomSHA256.enc.Hex);
};
reader.readAsArrayBuffer(controller.file);

Regarding our discussion in the comments: the issue stemmed from the fact that crypto-js does not support binary files, but rather operates on strings.

If you require a SHA256 implementation that directly supports ArrayBuffers, you may want to explore custom-sha256.

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

AngularJS throwing error due to additional content following the document element during XML parsing

I've been working with Angular JS and recently created a basic login form with routing to navigate to the next page upon successful login. However, I've encountered an issue when trying to implement conditional routing. Although I can successful ...

Having trouble loading this JSON data into my table

So I have a little challenge on my hands: I've got a JSON file with information about various books, each including details like title, author, and year of publication. The goal is to select an option from the list and display the chosen property in ...

How can I utilize React to pull information from the Google Taxonomy API?

Seeking assistance with React development, as I am a beginner and looking to retrieve data from this URL and organize it into a tree structure. I not only want to fetch the data but also display it in a tree format. My current code successfully retrieves t ...

In the provided Javascript snippet, how would you classify `word` - a function, variable, or object?

Understanding that an object is a variable and a function is a type of object, I find myself confused about the proper way to reference word in the following code snippet: var word; exports.setWord = function(c, ch){ word = c.get('chats')[ch]; ...

Issues with implementing ng-show and ng-disabled functions in AngularJS

I am currently working on a simple demo HTML page that involves client side form validation. My goal is to incorporate Bootstrap, AngularJS, and jQuery into this project, even though I am relatively new to AngularJS. However, I am facing some issues with ...

How to assign various column values to a PHP array in JSON format from a MySQL database

I am struggling with making a JSON Ajax request and receiving an array in return. After browsing through multiple questions, I came across this code snippet that I edited to fit my problem: var hej[]; function ajax_search(){ $.getJSON('test.php ...

The options for answering (True, False, Yes, and No) are not currently visible

I am struggling with displaying buttons for "True", "False", "Yes", and "No" in an appended row. Here is the application: Application To use the application, follow these steps: 1. Open the application and click on the green plus button. A modal window ...

Calling gtag("event") from an API route in NextJS

Is there a way to log an event on Google Analytics when an API route is accessed? Currently, my gtag implementation looks like this: export const logEvent = ({ action, category, label, value }: LogEventProps) => { (window as any).gtag("event&quo ...

Why isn't the mounted() lifecycle hook being triggered in my Vue 3 component?

I am struggling with a simple Vue 3 component that closely resembles some examples in the documentation. Here is the code: // Typewriter.vue <template> <div id="wrapper"> <p>{{ text }}</p> </div> </templa ...

Tips for transferring a JavaScript variable to a Java servlet using the doPost method

I am working with an HTML table that contains dropdowns. When a user clicks on a dropdown, I store the column name and corresponding row (billdate) in a variable. Now, my goal is to pass this variable to my Java servlet's doPost method and then use it ...

How can I use JavaScript to sort through an array and organize the data into groups?

Below is an array that I currently have: Status=["active","inactive","pending","active","completed","cancelled","active","completed"] I am looking to achieve the following result: StatusInfo=["active":3,"inactive":2,"pending":1, "completed":2, "cancelle ...

Leveraging the power of JavaScript functions together with the asp:Timer component

<p><b> Progress: <asp:Label ID="progressPercentageLabel" runat="server"></asp:Label>%</b></p> <script> function updateBar() { var bar = document.getElementById("CompletionBar"); ...

Angular JS is throwing an error because angular.model is not recognized as a function

I am experimenting with some angular JS examples, but I have encountered an error that is causing me some trouble. Can someone please assist me in resolving this issue? <html> <head> <script src="http://ajax.googleapis.com/ajax/li ...

The ng-click feature in AngularJS seems to be malfunctioning

Having trouble with ng-click not executing a function in the controller. Can someone provide assistance with this issue? <div class="buttonpanel" id ="btn-panel"> <div class="btn blue" ng-Click='send_data()'><a>Save</a&g ...

What is the best way to access event.target as an object in Angular 2?

Apologies for my limited English proficiency. . I am trying to write code that will call myFunction() when the user clicks anywhere except on an element with the class .do-not-click-here. Here is the code I have written: document.addEventListener(' ...

The dataLayer in Google Tag Manager is failing to trigger the necessary event

Product Purchase Button: <button id="btnBuy" onclick="SendData();" JavaScript function to track product details: <script> var dataLayer = []; dataLayer.push( { 'ecommerce': { 'detail': { 'actionField' ...

Tips for getting information from firestore by implementing a where clause specific to a field within an object?

In my React Native project, I am utilizing Firebase Firestore as the backend database. I have successfully retrieved data from the database using the following code: unsubscribe = firebase.firestore().collection('messages').where('user&apos ...

Tips for maintaining the state of a page submitted via Turbolinks using Rails 5 and jQuery

My current challenge involves toggling the visibility of a section when a specific element is clicked. Initially, I was able to achieve this functionality successfully. However, complications arose as my application revolves around a todo list where tasks ...

Prevent event bubbling on a link generated by an Angular directive that includes transclusion

I am currently developing a directive that adds a link to a DIV element through transclusion. However, I am facing an issue where I want to execute specific functionality when the link is clicked without being redirected to the dummy href (in this case goo ...

Is it acceptable to incorporate Node.js modules for utilization in Next.js?

Here's a funny question for you. I am trying to generate UUID in my Next.js project without adding any unnecessary packages. So, I decided to import crypto in my component like this: import crypto from 'crypto'; After importing it, I used i ...