2017-06-12 14 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);