Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs 6.10.2 crypto AES Invalid key length

I try to use crypto to encrypt a file. Here is my code:

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

I got the error:

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)

I though the sharedSecret length should be same as aes-length but it's not. What length should I use? Thanks :)

like image 933
Li Jinyao Avatar asked Jun 12 '17 15:06

Li Jinyao


1 Answers

You have bytes confused with bits. aes-256 means 256 bits = 32 bytes.

Try this:

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

If you can't see the difference, the change is:

const sharedSecret = crypto.randomBytes(32);

like image 108
Rohit Saxena Avatar answered Nov 07 '22 06:11

Rohit Saxena