Kaker
Kaker

Reputation: 645

NodeJS/JS How to correctly hash object json and string (concatenation) via sha256

Good morning,
I want to hash object params and string (concatenation) via sha256., but I do not know how to do it correctly.
My object:

var params = {
   "name": "kacper",
   "age": 23
};
var string = "string to hash";

I used for it library sha256 from npm, but my encode hash is incorectly.
Attempt hash:

var sha256 = require('sha256');
var hashing = sha256(params+stirng);
console.log(hashing);


Thans for yours help.

Upvotes: 1

Views: 3771

Answers (1)

Bary12
Bary12

Reputation: 1088

Let's first understand what params+string does exactly. params is converted into a string, resulting in [object Object]. Then your final string is [object Object]string to hash.

Instead, you might want to get the entire params object as a string. This can be done with JSON.stringify.

console.log(JSON.stringify(params) + string);

the result is then {"name":"kacper","age":23}string to hash.

Is this what you were looking for? It might be a better practice to make an object with params and string as fields.

var obj = {
  "params": {
    "name": "kacper",
    "age": 23
  },
  "string": "string to hash"
}

console.log(sha256(JSON.stringify(obj)));

Upvotes: 1

Related Questions