如何在JS中进行私有变换

时间:2018-04-11 06:04:23

标签: javascript node.js

我想在需要文件/模块时保存私有变量(秘密)。秘密应保存在"对象"文件sec_test.js,它不能是可执行的可读或可写的。这是正确的方法吗?

问题1: 是否有可能在执行期间以某种方式从testing_sec_test.js获取秘密?

问题2: 是否可以在sec_test.js中使用constructor-ish函数?

file:sec_test.js

module.exports = function (string) {
    var module = {};
    let secret = null;


    module.get_secret_length = function (callback) {
        generate_secret();
        if(secret == null){
            const json_err = {
                "Success":false,
                "error":"generating secret failed"
            };
            callback(json_err,null);
        }else{
            const json_err = {
                "Success":true,
                "result":"secret has been generated",
                "secret_length":get_secret_length()
            };
            callback(json_err,null);
        }
    }

    function generate_secret(){
        if(secret == null){
            secret = getRandomString()+string+getRandomString(); 
        } 
    }

    function get_secret_length(){
        return secret.length; 
   }

    function getRandomString(){
        const length = Math.floor(Math.random() * Math.floor(200));
        const characters_allowed = '@1#2$3&/=?:.;,+_-><~*^|4567890'+
        'qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM';
        let random_string = "";
        for(let i =0;i<length;i++){
            let random_nbr = Math.floor(Math.random() * Math.floor(characters_allowed.length));
            random_string += characters_allowed.charAt(random_nbr);
        }
        return random_string;
    }


    return module;
};

file:testing_sec_test.js

const sec_test = require('./sec_test')("IS THIS SECRET A PRIVATE VARIABLE");

console.log(sec_test.get_secret_length.toString());

sec_test.get_secret_length(function(err,result){
    if(err){
        console.log(err);
    }else{
        console.log(result);
    }
});

----------------------------------------------- ----------------

我猜我必须更好地提出我的问题,对不起

问题1:是否可以在需要对象并且参数已被输入后获取密钥或ivKey。或者这个对象不安全使用,因为它的密钥或ivKey是公共可访问的?

file:testing_sec_test.js

//lets pretend that these keys is written in from the terminal to the object and are NOT hardcoded in the code!.
let sec_Obj = {
    "key": '1234zr3p67VC61jmV54rIYu1545x4TlY',
    "ivKey": "123460iP0h6vJoEa",
    "salt": "1kg8kfjfd2js93zg7sdg485sd74g63d2",
    "key_iterations": 87923   
  }

const sec_test = require('./sec_test')(sec_Obj);
sec_Obj = null;

console.log(sec_test);
let plain_text = "This is a national secret";
console.log("plain_text == "+plain_text);
sec_test.encrypt(plain_text,function(err,encrypted){
    if(err){
        console.log(err);
    }else{
        console.log("encrypted == "+encrypted);
        sec_test.decrypt(encrypted,function(err,decrypted){
            if(err){
                console.log(err);
            }else{
                console.log("decrypted == "+decrypted);
            }
        });      

    }
});

file:sec_test.js

const crypto = require('crypto');
module.exports = function (keysObj) {
    //is the parameter keysObj private?? 
    var module = {};

    module.encrypt = function (clearData,callback) {
        let str_encoding = "utf8";
        let encoding = "base64";
        try {
            let encipher = crypto.createCipheriv('aes-256-ctr', getPrivateKey(), getPrivateIvKey());
            let result = encipher.update(clearData, str_encoding, encoding);
            result += encipher.final(encoding);
            callback(null,result);
        } catch (error) {
            callback({"success":false,"error":error},null);
        }   
    }

    module.decrypt = function(encrypted,callback) {
        let str_encoding = "utf8";
        let encoding = "base64";
        try {
            let decipher = crypto.createDecipheriv('aes-256-ctr',getPrivateKey(), getPrivateIvKey());
            let result = decipher.update(encrypted, encoding, str_encoding);
            result += decipher.final(str_encoding);       
            callback(null,result);
        } catch (error) {
            callback({"success":false,"error":error},null);            
        }
    }

    //is this a private function
    function getPrivateKey(){
        return crypto.pbkdf2Sync(keysObj['key'], keysObj['salt'], keysObj['key_iterations'], 32, 'sha512');
    }

    //is this a private function
    function getPrivateIvKey(){
        return new Buffer(keysObj['ivKey']);
    }

    return module;
};

1 个答案:

答案 0 :(得分:3)

简单示例

var privateVar = 'private';


module.exports = {

   test:function(){
       console.log('I am '+privateVar);
    }
}

var test = require('./test.js');

//logs i am private
test.test()
//logs undefined
test.privateVar