Search code examples
node.jscryptojs

How to use crpyto in NodeJs


I am learning NodeJs, and I am trying to implement the crypto library to encrypt and decrpty text,
I am referring the following example - https://www.w3schools.com/nodejs/ref_crypto.asp

The code to encrypt is as follows -

var crypto = require('crypto');

var mykey = crypto.createCipher('aes-128-cbc', 'mypassword');
var mystr = mykey.update('abc', 'utf8', 'hex')
mystr += mykey.update.final('hex');

console.log(mystr); 

The code to decrypt is as follows -

var crypto = require('crypto');

var mykey = crypto.createDecipher('aes-128-cbc', 'mypassword');
var mystr = mykey.update('34feb914c099df25794bf9ccb85bea72', 'hex', 'utf8')
mystr += mykey.update.final('utf8');

console.log(mystr);

The code samples seem to work on their environment,
But I am getting the following error when I try to run the same code on my machine -

mystr += mykey.update.final('hex');
                      ^

TypeError: mykey.update.final is not a function
    at Object.<anonymous> (/home/user/office/pocs/node-apps/sample-apps/Apps/crypto.js:5:23)
    at Module._compile (internal/modules/cjs/loader.js:734:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:745:10)
    at Module.load (internal/modules/cjs/loader.js:626:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:566:12)
    at Function.Module._load (internal/modules/cjs/loader.js:558:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:797:12)
    at executeUserCode (internal/bootstrap/node.js:526:15)
    at startMainThreadExecution (internal/bootstrap/node.js:439:3)

Can someone help implement it correctly to encrypt and decrytp text?
What am I doing wrong?


Solution

  • update line

    mystr += mykey.update.final('hex');
    

    to

    mystr += mykey.final("hex");
    

    Tried the code according to official documentation