Home > Blockchain >  Why is the hash of an object staying the same when I change its data?
Why is the hash of an object staying the same when I change its data?

Time:02-16

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 my 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);
        // var hash = CryptoJS.SHA256(hashRequest).toString();
        // hash = hash.toString(CryptoJS.enc.Base64);
        return hash;
    } catch (error) {
        console.log("Error : ", error);
    }
});

CodePudding user response:

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.

  • Related