Home > Mobile >  Error: Invalid key length and Error: Invalid IV length using AES-256-CBC algorithm
Error: Invalid key length and Error: Invalid IV length using AES-256-CBC algorithm

Time:05-19

I have 2 functions to encrypt and decrypt with AES-256-CBC algorithm:

import * as crypto from "crypto";

export const encrypt = (text: string, key: string, iv: string) => {
    const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
    let result = cipher.update(text, "utf8", "hex");
    result  = cipher.final("hex");

    return result;
};

export const decrypt = (text: string, key: string, iv: string) => {
    const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
    let result = decipher.update(text, "hex", "utf8");
    result  = decipher.final("utf8");

    return result;
};

The problem is with key and IV. I had to generate IV and key like this:

crypto.randomBytes(8).toString('hex') // IV
crypto.randomBytes(16).toString('hex') // Key

I was trying to change length like this, but had 2 errors:

crypto.randomBytes(16).toString('hex') // IV
crypto.randomBytes(32).toString('hex') // Key

Error: Invalid key length and Error: Invalid IV length

But I have found that key has to have 32 bytes, not 16. What's wrong?

CodePudding user response:

You are incorrectly hex-encoding your key and IV. Drop toString('hex') from both, these arguments must not be hex-encoded.

The correct length of the key and IV is 32 and 16 bytes respectively. By hex-encoding the strings, you're producing strings twice as long as is required, where each single byte goes from a value between 0 and 255 to a two character hex representation between between 00 and ff.

For example, the byte array [255, 255, 255] becomes the character array ['f', 'f', 'f', 'f', 'f', 'f'].

  • Related