Javascript 如何在JS中实现私有变量

Javascript 如何在JS中实现私有变量,javascript,node.js,Javascript,Node.js,我想在需要文件/模块时保存一个私有变量(secret)。该秘密应保存在文件sec_test.js的“object”中,且仅在执行时不可读写。这是正确的方法吗 问题1: 是否有可能在执行过程中从testing_sec_test.js获取秘密 问题2: 是否可以在sec_test.js中使用构造函数ish函数 文件:sec_test.js module.exports = function (string) { var module = {}; let secret = null;

我想在需要文件/模块时保存一个私有变量(secret)。该秘密应保存在文件sec_test.js的“object”中,且仅在执行时不可读写。这是正确的方法吗

问题1: 是否有可能在执行过程中从testing_sec_test.js获取秘密

问题2: 是否可以在sec_test.js中使用构造函数ish函数

文件: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;
};
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);
    }
});
//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);
            }
        });      

    }
});
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:是否可以在需要对象并输入参数后获取密钥或ivKey。或者,由于该对象的密钥或ivKey是可公开访问的,因此使用该对象是否不安全


文件:testing_secu_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;
};
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);
    }
});
//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);
            }
        });      

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

文件: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;
};
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);
    }
});
//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);
            }
        });      

    }
});
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;
};
简单例子

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 
简单例子

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 

如果它不可读,那么您希望
require()
如何工作?我的意思是,我只希望它在Secu test中可读,而不是在其他地方,它将无法在文件/对象之外获取该变量。与Java类似,私有字符串机密。但是在java中,我会使用cobstructor和公共类secu Test{private String secret=null;Public secu Test(String secret){this.secret=secret;}}}如果它不可读,那么你希望
require()
如何工作呢,不能在文件/对象之外获取该变量。与Java类似,私有字符串机密。但在java中,我将使用cobstructor和公共类secu Test{private String secret=null;Public secu Test(String secret){this.secret=secret;}}