如何在 Node Js 中使用加密
How to use crpyto in NodeJs
我正在学习 NodeJs,我正在尝试实现加密库来加密和解密文本,
我指的是以下示例 -
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)
谁能帮忙正确实现加密和解密文本?
我哪里做错了?
更新行
mystr += mykey.update.final('hex');
至
mystr += mykey.final("hex");
试了下代码
official documentation
我正在学习 NodeJs,我正在尝试实现加密库来加密和解密文本,
我指的是以下示例 -
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)
谁能帮忙正确实现加密和解密文本?
我哪里做错了?
更新行
mystr += mykey.update.final('hex');
至
mystr += mykey.final("hex");
试了下代码 official documentation