有人可以说如何加密和解密node.js中的jsonfile。我尝试了这个程序,它显示一个错误,因为文件密码tty.setrawmode不是一个函数。
纯文本文件:
{
"production" : {
"db" : {
"database" : "mysql",
"user" : "root",
"password" : "bdwb ve13hb3"
},
"app" : {
"port" : 8086
}
}
}
加密:
var SecureConf = require('secure-conf');
var sconf = new SecureConf();
sconf.encryptFile(
"./test.json",
"./test.json.enc",
function(err, f, ef, ec) {
if (err) {
consoel.log("failed to encrypt %s, error is %s", f, err);
} else {
console.log("encrypt %s to %s complete.", f, ef);
console.log("encrypted contents are %s", ec);
}
}
);
解密:
var SecureConf = require('secure-conf');
var sconf = new SecureConf();
var ef = "./test.json.enc";
var express = require('express');
var app = express();
sconf.decryptFile(ef, function(err, file, content) {
if (err) {
console.log('Unable to retrieve the configuration contents.');
} else {
var config = JSON.parse(content);
app.listen(config.production.app.port);
}
});
答案 0 :(得分:0)
如果使用三个参数调用sconf.encryptFile
,它将从终端读取密码。如果您没有在能够接受node.js中用户字符的终端中运行它,那么您需要在第三个参数的位置将密码添加到脚本中:
sconf.encryptFile(
"./test.json",
"./test.json.enc",
"this is not such a good password",
function(err, f, ef, ec) {
if (err) {
consoel.log("failed to encrypt %s, error is %s", f, err);
} else {
console.log("encrypt %s to %s complete.", f, ef);
console.log("encrypted contents are %s", ec);
}
}
);
需要为解密提供完全相同的密码。
当然,在代码中添加密码并不是一个好主意,因为攻击者只需查看代码即可找到用于加密配置文件的密码。