Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

713
Views
Error: Invalid key length and Error: Invalid IV length using AES-256-CBC algorithm

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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'].

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!