Search code examples
node.jsjsonencryptionsha1cryptojs

encrypt object as JSON format not working well


I try to encrypt data (json format) with crypto,

Here is my code:

const crypto = require('crypto');

let data = {
    aaa: "aaa",
    bbb: "bbb"};

let jsonData = JSON.stringify(data, null, 2);
 encrypt(jsonData);

function encrypt(data) {
    let hmac = crypto.createHmac('sha1', 'abc');
    console.log(data);
    hmac.update(data);
    let key = hmac.digest('hex');
    console.log(key);
}

log:

{
  "aaa": "aaa",
  "bbb": "bbb"
}
820c9d3d82a9a8fc1cc0352929ccccdfd945c5d0

When I copy the data from the log and paste it in this site, I get another signature :

enter image description here

enter image description here

What is wrong?


Solution

  • I found the problem, as soon as I added:

    .replace (/\n/ g, '\r\n')
    

    It worked fine.

    Here is the fixed code :

    function encrypt(data) {
        let hmac = crypto.createHmac('sha1', 'abc');
        console.log(data);
        hmac.update(data.replace(/\n/g, '\r\n'));
        let key = hmac.digest('hex');
        console.log(key);
        console.log("#################################################");
    }