2017-07-15 73 views
0

產生crypto.createCipheriv論據我使用下面的代碼來加密在我的Node.js代碼串。如何從靜態源

我想了解如何從靜態源生成KEYHMAC_KEY。在我的程序中,它現在是隨機生成的。由於它是隨機生成的,因此我無法使用以下算法來加密我的數據庫密碼。

crypto = require('crypto'); 

ALGORITHM = "AES-256-CBC"; 
HMAC_ALGORITHM = "SHA256"; 
KEY = crypto.randomBytes(32); 
HMAC_KEY = crypto.randomBytes(32); 

function (plain_text) {  
    var IV = new Buffer(crypto.randomBytes(16)); // ensure that the IV (initialization vector) is random 
    var cipher_text; 
    var hmac; 
    var encryptor; 

    encryptor = crypto.createCipheriv(ALGORITHM, KEY, IV); 
    encryptor.setEncoding('hex'); 
    encryptor.write(plain_text); 
    encryptor.end(); 

    cipher_text = encryptor.read(); 

    hmac = crypto.createHmac(HMAC_ALGORITHM, HMAC_KEY); 
    hmac.update(cipher_text); 
    hmac.update(IV.toString('hex')); // ensure that both the IV and the cipher-text is protected by the HMAC 

    // The IV isn't a secret so it can be stored along side everything else 
    return cipher_text + "$" + IV.toString('hex') + "$" + hmac.digest('hex') 

}; 

回答

0

你必須對你的代碼分成兩個執行:產生你的鑰匙,並將其顯示在一個可存儲格式,使用存儲的密鑰

KEY = crypto.randomBytes(32); 
HMAC_KEY = crypto.randomBytes(32); 
console.log(KEY.toString('hex')); 
console.log(HMAC_KEY.toString('hex')); 
  • 代碼

    1. 代碼

      KEY = Buffer.from('some key string', 'hex'); 
      HMAC_KEY = Buffer.from('some other key string', 'hex'); 
      

    你一定要確保你的鑰匙實際上並不在你的代碼,而是在一些文件,因爲硬編碼在代碼中的關鍵和他們檢查到您的版本控制系統是一個壞主意,並可能給你的開發人員訪問到他們可能不應該擁有的生產系統。

  • +0

    感謝。不幸的是我得到一個錯誤「錯誤:無效的密鑰長度」使用KEY = Buffer.from(「爲abcdefghijklmnopqrstuvwxyzabcdef」,「六角」)之後;正如你所建議的那樣。我哪裏錯了?你能指導我嗎? –

    +0

    它改變後開始工作KEY = Buffer.from('some key string','hex');到KEY = Buffer.from('一些關鍵字符串','二進制'); –

    +0

    您應該使用第1步中顯示的相同密鑰字符串 –