2017-06-12 206 views
0

我嘗試使用加密來加密文件。這裏是我的代碼:Nodejs 6.10.2 crypto AES密鑰長度無效

const crypto = require('crypto'); 
const fs = require('fs'); 

const input = fs.createReadStream('test.jpg'); 
const output = fs.createWriteStream('test.enc'); 

const sharedSecret = crypto.randomBytes(256); 
const initializationVector = crypto.randomBytes(16); 

const cipher = crypto.createCipheriv('aes-256-cbc', sharedSecret, initializationVector); 

input.pipe(cipher).pipe(output); 

我得到了錯誤:

crypto.js:191 
    this._handle.initiv(cipher, toBuf(key), toBuf(iv)); 
      ^

Error: Invalid key length 
    at Error (native) 
    at new Cipheriv (crypto.js:191:16) 
    at Object.Cipheriv (crypto.js:189:12) 
    at Object.<anonymous> (/Users/lijinyao/Projects/HyperAlbum/Encryption/encrypt.js:10:23) 
    at Module._compile (module.js:570:32) 
    at Object.Module._extensions..js (module.js:579:10) 
    at Module.load (module.js:487:32) 
    at tryModuleLoad (module.js:446:12) 
    at Function.Module._load (module.js:438:3) 
    at Module.runMain (module.js:604:10) 

我雖然sharedSecret長度應該是相同的AES-長度,但事實並非如此。我應該使用多長時間?謝謝:)

+0

OMG,我看着辦吧,長傳球randomBytes要分8,因爲它是字節而不是位。 –

回答

1

你有字節與位混淆。 aes-256表示256位= 32字節。

試試這個:

const crypto = require('crypto'); 
const fs = require('fs'); 

const input = fs.createReadStream('test.jpg'); 
const output = fs.createWriteStream('test.enc'); 

const sharedSecret = crypto.randomBytes(32); 
const initializationVector = crypto.randomBytes(16); 

const cipher = crypto.createCipheriv('aes-256-cbc', sharedSecret, initializationVector); 

input.pipe(cipher).pipe(output); 

如果你不能看到的不同,變化爲:

const sharedSecret = crypto.randomBytes(32);