2017-03-14 36 views
-2

任何人都可以說如何加密和解密node.js中的jsonfile。我試過這個程序,它顯示一個錯誤,因爲文件密碼tty.setrawmode不是一個函數。加密和解密node.js中的json文件

明文文件:

{ 
    "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

如果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); 
     } 
    } 
);

的需要爲解密提供完全相同的密碼。

當然,將密碼添加到代碼中並不是一個好主意,因爲攻擊者只需查看代碼即可找到用於加密配置文件的密碼。

+0

兄弟,我無法得到輸出。我按照你的指示。我添加了第三個參數作爲文本。我運行加密程序作爲webstorm終端中的第一個。它顯示相同的錯誤。你給我發送確切的代碼加密和解密。這是我的郵件ID:[email protected]提前。我在等待您的回覆... – vigneshRavi

+0

對不起,但我不是你的兄弟。我偷看了'sconf.encryptFile'的源代碼,這是應該發生的事情。我沒有真正運行這個代碼。 –