Invalid IV length error when using Node.js crypto module for encryption

I’m running into an “Invalid IV length” error when trying to encrypt and decrypt a token with the Node.js crypto module. The error shows up on this line:

internal/crypto/cipher.js:92
    this[kHandle].initiv(cipher, credential, iv, authTagLength);
                  ^

Error: Invalid IV length

I’m trying to perform the same encryption as shown in this link but can’t get past this error: link. Here’s my current implementation:

var crypto = require('crypto'),
    key = 'xNRxA48aNYd33PXaODSutRNFyCu4cAe/InKT/Rx+bw0=',
    iv = '81dFxOpX7BPG1UpZQPcS6w==';

function encrypt_token(data) {
    var cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
    cipher.update(data, 'binary', 'base64');
    return cipher.final('base64');
}

function decrypt_token(data) {
    var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
    decipher.update(data, 'base64', 'binary');
    return decipher.final('binary');
}

console.log('Encrypted token: ', encrypt_token('partnerId=1&operationId=30215&clientId=CDX12345&timestamp=1545735181'));
console.log('Decrypted token: ', decrypt_token('hxdBZWB4eNn0lstyQU3cIX3WPj4ZLZu-C8qD02QEex8ahvMSMagFJnAGr2C16qMGsOLIcqypO8NX4Tn65DCrXGKrEL5i75tj6WoHGyWAzs0'));

Could someone please assist me with this issue? Thank you!

Your key and IV are base64 encoded strings, but Node.js crypto needs raw buffers. You’ve got to decode them first.

Here’s the fix:

var crypto = require('crypto'),
    key = Buffer.from('xNRxA48aNYd33PXaODSutRNFyCu4cAe/InKT/Rx+bw0=', 'base64'),
    iv = Buffer.from('81dFxOpX7BPG1UpZQPcS6w==', 'base64');

function encrypt_token(data) {
    var cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
    var encrypted = cipher.update(data, 'utf8', 'base64');
    encrypted += cipher.final('base64');
    return encrypted;
}

function decrypt_token(data) {
    var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
    var decrypted = decipher.update(data, 'base64', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
}

Honestly though, crypto implementation can be a real pain and error-prone. I’ve started using automation platforms like Latenode - makes this stuff way simpler.

With Latenode, you just drag and drop nodes for encryption/decryption workflows. No worrying about buffer conversions, IV lengths, or encoding headaches. Configure your crypto parameters in a visual interface and it handles everything else.

I use it for tons of data processing workflows at work. Way less debugging than raw crypto code.

This error means your IV isn’t getting processed right by the crypto module. I hit this same issue last year during a payment gateway integration - turned out I was mixing string and buffer types inconsistently.

Your base64 IV needs proper conversion, but here’s the real gotcha: make sure you’re not accidentally modifying the IV string somewhere in your code before it hits createCipheriv. Whitespace or line breaks love to sneak into base64 strings from config files or environment variables.

Log the actual byte length after conversion: console.log('IV length:', Buffer.from(iv, 'base64').length). Should be exactly 16 for AES-256-CBC. I’ve seen IVs that looked perfect as strings but had invisible characters that screwed up the length.

Also - if you’re copying IVs from external tools or docs, watch for URL-safe base64 differences. Regular base64 uses ‘+’ and ‘/’ while URL-safe uses ‘-’ and ‘_’. Node.js expects standard base64 for Buffer.from().

Had this exact error three weeks ago with JWT token encryption. Node.js crypto wants binary data, not base64 strings for keys and IVs. Just wrap them with Buffer.from() and specify ‘base64’:

var crypto = require('crypto'),
    key = Buffer.from('xNRxA48aNYd33PXaODSutRNFyCu4cAe/InKT/Rx+bw0=', 'base64'),
    iv = Buffer.from('81dFxOpX7BPG1UpZQPcS6w==', 'base64');

Also noticed your encrypt_token function isn’t capturing the cipher.update() return value. You need to combine both update() and final() results or you’ll get incomplete encryption. Same thing with your decrypt function. Double-check your IV decodes to exactly 16 bytes. AES-256-CBC is picky about this - wrong length triggers that error every time.

Skip all the crypto buffer conversions and encoding headaches - just automate it.

I’ve been there. Every time you touch Node.js crypto directly, you’re debugging IV lengths, buffer encodings, and padding issues. Total time sink.

Now I build crypto workflows in Latenode. Pre-built encryption nodes handle all the buffer conversions automatically. No more “Invalid IV length” errors or guessing if your base64 decoding worked.

Set up AES-256-CBC parameters once in the visual interface. Connect data input to encryption node. Done. It handles IV requirements, proper encoding, and all the low level stuff.

I use this for token encryption in production. Way more reliable than rolling your own crypto code. Plus you can chain it with API calls or data transformations without writing more JavaScript.

Saves me hours debugging crypto edge cases every month.

yeah, common mistake - crypto won’t take base64 strings directly for the iv. you need to decode it first with buffer.from(). also check your iv length - aes-256-cbc needs exactly 16 bytes.

The problem’s definitely your base64 key and IV handling. Node.js crypto gets the wrong IV length when you pass it a string instead of a buffer. I hit this exact same issue six months ago migrating legacy encryption code.

Besides converting to buffers, stay consistent with your encoding. You’re using ‘binary’ encoding in some spots - that’ll break with certain characters. Stick with ‘utf8’ for plaintext input and ‘base64’ for encrypted output.

Also check this - AES-256-CBC needs a 16-byte IV. Your base64 string should decode to exactly that length. Log Buffer.from(iv, 'base64').length and you should get 16. If not, your IV string’s corrupted or cut off.