如何在NodeJ中使用crpyto

时间:2019-02-10 12:01:23

标签: node.js cryptojs

我正在学习NodeJ,并且正在尝试实现加密库来对文本进行加密和解密,
我指的是以下示例- https://www.w3schools.com/nodejs/ref_crypto.asp

要加密的代码如下-

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); 

要解密的代码如下-

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);

代码示例似乎可以在其环境中运行,
但是当我尝试在计算机上运行相同代码时出现以下错误-

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)

有人可以帮助正确实现它来加密和解密文本吗?
我在做什么错了?

1 个答案:

答案 0 :(得分:1)

更新行

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

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

根据 official documentation