Jersson G Arrivasplata Rojas
TipSeguridadNode.js1 min de lecturaActualizado 2026

Encriptación de datos críticos

A02:2021 — Fallos criptográficos

Cifrado autenticado con AES-256-GCM: la clave se deriva una sola vez de un secreto guardado fuera del código, y cada cifrado usa un IV nuevo.

javascript
const crypto = require("crypto");

const ALGORITHM = "aes-256-gcm";
// Secreto y salt desde variables de entorno, nunca en el código
const key = crypto.scryptSync(process.env.CRYPTO_PASSWORD, process.env.CRYPTO_SALT, 32);
javascript
const encrypt = (plainText) => {
  const iv = crypto.randomBytes(12); // IV único por cada cifrado
  const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
  const content = Buffer.concat([cipher.update(plainText, "utf8"), cipher.final()]);
  return {
    iv: iv.toString("hex"),
    content: content.toString("hex"),
    tag: cipher.getAuthTag().toString("hex")
  };
};

const decrypt = ({ iv, content, tag }) => {
  const decipher = crypto.createDecipheriv(ALGORITHM, key, Buffer.from(iv, "hex"));
  decipher.setAuthTag(Buffer.from(tag, "hex"));
  return Buffer.concat([
    decipher.update(Buffer.from(content, "hex")),
    decipher.final()
  ]).toString("utf8");
};

Aplicación: se encripta la cuenta bancaria antes de exponer el usuario y se desencripta con el mismo objeto {iv, content, tag}.

javascript
const showUser = (firstName, bankAcc) => {
  const user = {};
  if (firstName) user.firstName = firstName;
  if (bankAcc) user.bankAcc = encrypt(bankAcc);
  return user;
};

const user = showUser("Giomar", "0000000000000000");
console.log(user.bankAcc.content); // texto cifrado en hexadecimal
console.log(decrypt(user.bankAcc)); // "0000000000000000"

Actualizado 2026. La versión anterior usaba config.cryptoAlgo (no existía; el objeto definía cryptoAlgorithm), derivaba una clave nueva con salt aleatoria en cada cifrado y reutilizaba el mismo IV. Con GCM, reutilizar IV compromete la confidencialidad.

Jersson G. Arrivasplata RojasSoftware Engineer & Technical Leader · Lima, Perú
TipSecurityNode.js1 min readUpdated 2026

Encrypting critical data

A02:2021 — Cryptographic failures

Authenticated encryption with AES-256-GCM: the key is derived once from a secret kept outside the code, and each encryption uses a new IV.

javascript
const crypto = require("crypto");

const ALGORITHM = "aes-256-gcm";
// Secreto y salt desde variables de entorno, nunca en el código
const key = crypto.scryptSync(process.env.CRYPTO_PASSWORD, process.env.CRYPTO_SALT, 32);
javascript
const encrypt = (plainText) => {
  const iv = crypto.randomBytes(12); // IV único por cada cifrado
  const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
  const content = Buffer.concat([cipher.update(plainText, "utf8"), cipher.final()]);
  return {
    iv: iv.toString("hex"),
    content: content.toString("hex"),
    tag: cipher.getAuthTag().toString("hex")
  };
};

const decrypt = ({ iv, content, tag }) => {
  const decipher = crypto.createDecipheriv(ALGORITHM, key, Buffer.from(iv, "hex"));
  decipher.setAuthTag(Buffer.from(tag, "hex"));
  return Buffer.concat([
    decipher.update(Buffer.from(content, "hex")),
    decipher.final()
  ]).toString("utf8");
};

Usage: the bank account is encrypted before exposing the user and decrypted with the same {iv, content, tag} object.

javascript
const showUser = (firstName, bankAcc) => {
  const user = {};
  if (firstName) user.firstName = firstName;
  if (bankAcc) user.bankAcc = encrypt(bankAcc);
  return user;
};

const user = showUser("Giomar", "0000000000000000");
console.log(user.bankAcc.content); // texto cifrado en hexadecimal
console.log(decrypt(user.bankAcc)); // "0000000000000000"

Updated 2026. The previous version used config.cryptoAlgo (it did not exist; the object defined cryptoAlgorithm), derived a new key with a random salt on every encryption and reused the same IV. With GCM, reusing the IV compromises confidentiality.

Original post
Jersson G. Arrivasplata RojasSoftware Engineer & Technical Leader · Lima, Perú
TipSegurançaNode.js1 min de leituraAtualizado 2026

Criptografia de dados críticos

A02:2021 — Falhas criptográficas

Criptografia autenticada com AES-256-GCM: a chave é derivada uma única vez de um segredo guardado fora do código, e cada cifragem usa um IV novo.

javascript
const crypto = require("crypto");

const ALGORITHM = "aes-256-gcm";
// Secreto y salt desde variables de entorno, nunca en el código
const key = crypto.scryptSync(process.env.CRYPTO_PASSWORD, process.env.CRYPTO_SALT, 32);
javascript
const encrypt = (plainText) => {
  const iv = crypto.randomBytes(12); // IV único por cada cifrado
  const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
  const content = Buffer.concat([cipher.update(plainText, "utf8"), cipher.final()]);
  return {
    iv: iv.toString("hex"),
    content: content.toString("hex"),
    tag: cipher.getAuthTag().toString("hex")
  };
};

const decrypt = ({ iv, content, tag }) => {
  const decipher = crypto.createDecipheriv(ALGORITHM, key, Buffer.from(iv, "hex"));
  decipher.setAuthTag(Buffer.from(tag, "hex"));
  return Buffer.concat([
    decipher.update(Buffer.from(content, "hex")),
    decipher.final()
  ]).toString("utf8");
};

Aplicação: a conta bancária é criptografada antes de expor o usuário e descriptografada com o mesmo objeto {iv, content, tag}.

javascript
const showUser = (firstName, bankAcc) => {
  const user = {};
  if (firstName) user.firstName = firstName;
  if (bankAcc) user.bankAcc = encrypt(bankAcc);
  return user;
};

const user = showUser("Giomar", "0000000000000000");
console.log(user.bankAcc.content); // texto cifrado en hexadecimal
console.log(decrypt(user.bankAcc)); // "0000000000000000"

Atualizado 2026. A versão anterior usava config.cryptoAlgo (não existia; o objeto definia cryptoAlgorithm), derivava uma nova chave com salt aleatório a cada cifragem e reutilizava o mesmo IV. Com GCM, reutilizar o IV compromete a confidencialidade.

Jersson G. Arrivasplata RojasSoftware Engineer & Technical Leader · Lima, Perú

Apoya mis proyectos

Si una librería, guía o recurso de este sitio te fue útil, puedes aportar con Yape o Plin. Ayuda a mantener el código abierto y la documentación.

987 347 691Jersson G. Arrivasplata Rojas · Soles