Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

crypto.createCipheriv throws Invalid key length or Invalid IV length

ErrorRangeError: Invalid key length

Short answer

createCipheriv wants a key and an IV with exactly the byte length the chosen algorithm needs. Count bytes, not characters. aes-192-cbc needs a 24-byte key; a hex or base64 string must be decoded into a Buffer first, or it is read as UTF-8 text and has the wrong length. CBC also needs a 16-byte IV.

  • Applies to Node.js 22, Node.js 24
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Print the byte length of what you actually pass in. If you pass a string, the number you get here is what Node.js sees, and it is often not the number you expected.

    const key = process.env.CIPHER_KEY;
    console.log('as utf8 string:', Buffer.byteLength(key, 'utf8'));
    console.log('as hex:', Buffer.from(key, 'hex').length);
    console.log('as base64:', Buffer.from(key, 'base64').length);
  2. 2Match what you see, then jump to its fix

    1. 1ERR_CRYPTO_INVALID_KEYLENThe key length does not match the algorithmFix
    2. 2The key looks right in the .env file but the error still appearsA hex or base64 key was passed as a plain stringFix
    3. 3ERR_CRYPTO_INVALID_IV or Invalid initialization vectorThe IV has the wrong length (error says initialization vector)Fix

What does the error look like?

  • RangeError: Invalid key length
  • code: 'ERR_CRYPTO_INVALID_KEYLEN'
  • RangeError: Invalid initialization vector
  • code: 'ERR_CRYPTO_INVALID_IV'

Cause 1 of 3

The key length does not match the algorithm

1Check

The Node.js docs say the key length depends on the algorithm, and give aes192 as 24 bytes (192 bits). The number in the algorithm name is the key size in bits; divide by 8 for bytes. Node.js documents this error code as 'An invalid key length was provided.'

const algorithm = 'aes-192-cbc';   // 192 bits = 24 bytes
console.log(Buffer.byteLength(key));

2Fix

Derive a key of the exact size from a password with scrypt, instead of padding or cutting a string by hand. The third argument of scryptSync is the key length in bytes.

const { scryptSync } = require('node:crypto');
const key = scryptSync(password, 'salt', 24); // 24 bytes for aes-192-cbc

3Verify

The cipher is created without a throw.

const { createCipheriv } = require('node:crypto');
createCipheriv('aes-192-cbc', key, iv);

Confirmed by nodejs.org

Did this fix it?

Cause 2 of 3

A hex or base64 key was passed as a plain string

1Check

The docs state that a string key is decoded with options.encoding, which defaults to utf8. So a 64-character hex string is read as 64 bytes of text, not as the 32 bytes it encodes.

console.log(Buffer.byteLength(key, 'utf8'));  // 64 for a 64-char hex string
console.log(Buffer.from(key, 'hex').length);  // 32

2Fix

Decode the string into a Buffer yourself before you pass it in.

const key = Buffer.from(process.env.CIPHER_KEY, 'hex'); // 32 bytes for aes-256
const cipher = createCipheriv('aes-256-cbc', key, iv);

3Verify

Buffer length equals the algorithm's key size in bytes.

node -e "console.log(Buffer.from('00'.repeat(32),'hex').length)"

Confirmed by nodejs.org

Did this fix it?

Cause 3 of 3

The IV has the wrong length (error says initialization vector)

1Check

Node.js documents this code as 'An invalid initialization vector was provided.' IV rules depend on the algorithm; the docs' aes-192-cbc example uses a 16-byte IV. Strings passed as iv are always decoded as UTF-8.

console.log(iv.length);

2Fix

Generate a fresh random IV of the right size for each message and store it next to the ciphertext. Check the IV rules of your algorithm before you pick a size.

const { randomFillSync } = require('node:crypto');
const iv = randomFillSync(new Uint8Array(16)); // 16 bytes for the aes-192-cbc example

3Verify

createCipheriv no longer throws and iv.length is 16 for CBC.

console.log(iv.length);

Confirmed by nodejs.org

Did this fix it?

How do I stop it coming back?

  • Keep the key as hex or base64 in config and decode it to a Buffer in one helper, so every caller gets the same bytes.
  • Never use a short password as a key. Derive the key with scrypt and a salt.
  • Add a startup check that compares the key's byte length with the algorithm and fails with a clear message.
  • Make a new random IV for every encryption instead of reusing one.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

ng serve says it cannot determine the project or target

Cannot determine project for command.

The Angular CLI looked through angular.json for a project that defines the target you asked for (serve, build, test) and found none, or found several and could not pick one.

3 causes, each with a fix

Back end

ng serve cannot find the dev-server builder package

Could not find the implementation for builder @angular/build:dev-server

The builder named in angular.json (for example @angular-devkit/build-angular:dev-server) is looked up as an npm package starting from the workspace root.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.