Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid key length in crypto.createCipheriv

Tags:

I generated a base64-encoded key using this code in NodeJS v8.11.0:

const secret = 'shezhuansauce';
const key = crypto.createHash('sha256').update(String(secret)).digest('base64');
//output is REtgV24bDB7xQYoMuypiBASMEaJbc59nJWChoXbbmsA=

Using the key, I try to encrypt a string:

var tobeEncrypted = 'some secret string';
const iv = crypto.randomBytes(16).toString('hex').slice(0, 16);
const cipher = crypto.createCipheriv('aes-256-ctr', key, iv);
const encrypted = cipher.update(String(tobeEncrypted), 'utf8', 'hex') + cipher.final('hex');
console.log(encrypted);

However, I received an error:

crypto.js:219
this._handle.initiv(cipher, toBuf(key), toBuf(iv));
           ^
Error: Invalid key length

The key needs to be base64 string as I will store it in a Cloud service and it only receives base64 string.

Any help is appreciated.

like image 662
user1055010 Avatar asked Jun 21 '18 07:06

user1055010


People also ask

What is IV in createCipheriv?

createCipheriv() method will first create and then return the cipher object as per the algorithm passed for the given key and authorization factor (iv).

What is cipher update?

The cipher.update() is used to update the cipher with the receivd data according to the given encoding format. It is one of the inbuilt method that is provided by the class Cipher within the crypto module. If an input encoding is specified, the data argument is a string, else the data argument is a buffer.


2 Answers

Just add a tip: Key length is dependent on the algorithm, such as for aes192, it's 24 bytes, or aes256, it's 32 bytes. You need to have a key length of 32 byte (256 bit). So if you change your key line to:

let key = crypto.createHash('sha256').update(String(secret)).digest('base64').substr(0, 32);

it will work.

like image 78
tur1ng Avatar answered Sep 21 '22 22:09

tur1ng


You said you stored a key in BASE 64 and the key is 256 bits (or 32 bytes) (which we see that you computed sha256), so simply get that base64 key, then you can get the bytes easily like this:

const key_in_bytes = Buffer.from(BASE_64_KEY, 'base64')

And you can use this key in bytes as your key as:

const cipher = crypto.createCipheriv('aes-256-ctr', key_in_bytes, iv);
like image 42
Truly Avatar answered Sep 20 '22 22:09

Truly