我是Node js的新手。 尝试运行一个简单的Node Js代码来加密字符串:
module.path.push('./node_modules');
var Cryptr = require("./node-crypt"),
cryptr = new Cryptr('myTotalySecretKey');
var encryptedString = cryptr.encrypt('bacon');
cryptr.decrypt(encryptedString);
获取错误:
module.path.push('./node_modules');
^
TypeError: Cannot read property 'push' of undefined
at Object.<anonymous> (D:\node samples\sample.js:3:13)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:191:16)
at bootstrap_node.js:612:3
请帮助我。我只想加密和解密字符串。
答案 0 :(得分:0)
来自:https://www.w3schools.com/nodejs/ref_crypto.asp 加密示例(从2018-09开始无效):
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); //34feb914c099df25794bf9ccb85bea72
同意参考的样品无效。使用更高版本的API更新了加密
var crypto = require('crypto');
var cipher = crypto.createCipher('aes-128-cbc', 'mypassword');
var encrypted = cipher.update('abc', 'utf8', 'hex')
encrypted += cipher.final('hex')
console.log(encrypted);
散列示例: 发件人:https://node.readthedocs.io/en/latest/api/crypto/
var filename = process.argv[2];
var crypto = require('crypto');
var fs = require('fs');
var shasum = crypto.createHash('sha1');
var s = fs.createReadStream(filename);
s.on('data', function(d) {
shasum.update(d);
});
s.on('end', function() {
var d = shasum.digest('hex');
console.log(d + ' ' + filename);
});
更新-不读取文件的普通HASH示例:
var crypto = require('crypto');
const plain = Buffer.from('some string', 'utf-8');
var shasum = crypto.createHash('sha1');
shasum.update(plain);
var hash = shasum.digest('hex');
console.log(hash);
我同时展示了加密和散列以演示深度。加密可以“撤消”,而哈希不能。还要注意-并非所有加密都是一样的。算法和密钥长度是需要与您的问题相匹配的重要决策。
答案 1 :(得分:0)
我知道了,这是加密代码:
var crypto = require('crypto');
function encrypt(text){
var cipher = crypto.createCipher('aes-256-cbc','d6f3Efeq');
var crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex');
return crypted;
}
var c=encrypt('npci@123');
console.log("Encrypted string: "+c);