• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

187
Views
Why is the hash of an object staying the same when I change its data?

I have this code to hash an object.

I am saving this hash as a key in redis with a timeout but even if I change something in that incoming request object it is generating the same hash and redis shows there is same key already there.

Does this package have some trouble on hashing or does my code have any problem?

const asyncMiddleware = require('../middlewares/async');
var CryptoJS = require("crypto-js");
exports.hash = asyncMiddleware(async (hashRequest) => {
    try {
        var hash = CryptoJS.SHA256(hashRequest).toString(CryptoJS.enc.Base64);
        return hash;
    } catch (error) {
        console.log("Error : ", error);
    }
});
about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can't pass an Object to the SHA256 Method, you may only pass strings and WordArrays.

When you pass an object, cryptojs will run .toString() on it, which will always give the same output ([object Object]), and thus the same hash.

console.log(({a:1,b:1}).toString())
console.log(({a:1,b:2}).toString())

If you want to hash Objects, JSON.stringify() them:

const asyncMiddleware = require('../middlewares/async');
var CryptoJS = require("crypto-js");
exports.hash = asyncMiddleware(async (hashRequest) => {
    try {
        return CryptoJS.SHA256(JSON.stringify(hashRequest)).toString(CryptoJS.enc.Base64);
    } catch (error) {
        console.log("Error : ", error);
    }
});

See my repl again, for the difference.

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error