Invalid key length in crypto.createCipheriv

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.


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

an alternative approach which may be better than chopping the base 64 string into the first 32 bytes is to simply return the value of the key prior to the digest() call:

let key = crypto.createHash('sha256').update(String(secret))

If the key is cut to 32 bytes after converting it into base 64, that chopped string is an invalid base64 string.