Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

725
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda