Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Security and hardening

Node.js decipher.final() throws bad decrypt on stored data

Your error

Error: error:1C800064:Provider routines::bad decrypt1 more line it can show

Fix it fast

Most common cause, 1 of 4

The decrypting side builds a different key or IV

Derive the key the same way in both places and keep the IV with each record.

Fix
import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from 'node:crypto';

const key = scryptSync(process.env.ENC_PASSWORD, process.env.ENC_SALT, 32);

export function encrypt(text) {
  const iv = randomBytes(16);
  const cipher = createCipheriv('aes-256-cbc', key, iv);
  return Buffer.concat([iv, cipher.update(text, 'utf8'), cipher.final()]).toString('base64');
}

export function decrypt(stored) {
  const buf = Buffer.from(stored, 'base64');
  const decipher = createDecipheriv('aes-256-cbc', key, buf.subarray(0, 16));
  return Buffer.concat([decipher.update(buf.subarray(16)), decipher.final()]).toString('utf8');
}
Did this fix it?
Full steps for this cause: check, fix, verify

Short answer

error:1C800064:Provider routines::bad decrypt (ERR_OSSL_BAD_DECRYPT) comes from decipher.final() when the last block fails the padding check. On Node.js 22, 24 and 26 the key or IV differs from encryption, the stored ciphertext was decoded with the wrong encoding, or the sender used no standard padding. Decrypt once with setAutoPadding(false) to see which one.

  • Applies to Node.js 26.13 LTS, Node.js 24.22 LTS, Node.js 22.23, OpenSSL 3.5 bundled with Node.js
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Which cause do you have?

Run one decryption with padding checks turned off, giving the key, IV and ciphertext as hex exactly as your code produces them. The example assumes aes-256-cbc, so put your own cipher name there. A non-zero remainder (the script then stops at final) means the bytes were mangled on the way in, cause 2. Readable text with odd trailing bytes points to padding, cause 4. Unreadable output means the key material is wrong, cause 1 or 3.

Run this first
node -e '
const { createDecipheriv } = require("node:crypto");
const [key, iv, data] = process.argv.slice(1).map((h) => Buffer.from(h, "hex"));
console.log("length % 16 =", data.length % 16);
const d = createDecipheriv("aes-256-cbc", key, iv).setAutoPadding(false);
const out = Buffer.concat([d.update(data), d.final()]);
console.log("last block:", out.subarray(-16).toString("hex"));
console.log(out.toString("utf8"));
' "$KEY_HEX" "$IV_HEX" "$CIPHERTEXT_HEX"

Then find the line you see in this list and open its fix:

  1. 1The decrypting side builds a different key or IVWith padding off, the output is unreadable bytes even though the ciphertext length is a whole number of blocks
  2. 2Hex or base64 ciphertext is turned back into the wrong bytesThe stored value contains only 0-9 and a-f while the code decodes it as base64 or utf8, or the other way round
  3. 3Old records were written by the removed crypto.createCipher()The writing code called crypto.createCipher(algorithm, password) with no IV, and the reader now uses createDecipheriv()
  4. 4The other system encrypted without standard block paddingWith padding off the text is readable, but the last block ends in 00 bytes or carries no padding at all

What does the error look like?

  • Error: error:1C800064:Provider routines::bad decrypt
  • library: 'Provider routines', reason: 'bad decrypt', code: 'ERR_OSSL_BAD_DECRYPT'

Cause 1 of 4

The decrypting side builds a different key or IV

You seeWith padding off, the output is unreadable bytes even though the ciphertext length is a whole number of blocks

Check

Node.js raises bad decrypt when the key or IV given to createDecipheriv() is not the pair the encryptor used, because wrong key bytes leave random padding in the last block. Typical slips are a password run through another derivation function, a salt that changed, an IV generated fresh at read time instead of saved, or a hex key string read as utf8. Print a short fingerprint of the key on both machines and compare.

Check
node -e 'const { createHash } = require("node:crypto"); const k = Buffer.from(process.env.ENC_KEY, "hex"); console.log(k.length, createHash("sha256").update(k).digest("hex").slice(0, 12))'

Fix

Derive the key the same way in both places and keep the IV with each record. Placing a random 16-byte IV in front of the ciphertext lets every message carry its own IV safely.

Fix
import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from 'node:crypto';

const key = scryptSync(process.env.ENC_PASSWORD, process.env.ENC_SALT, 32);

export function encrypt(text) {
  const iv = randomBytes(16);
  const cipher = createCipheriv('aes-256-cbc', key, iv);
  return Buffer.concat([iv, cipher.update(text, 'utf8'), cipher.final()]).toString('base64');
}

export function decrypt(stored) {
  const buf = Buffer.from(stored, 'base64');
  const decipher = createDecipheriv('aes-256-cbc', key, buf.subarray(0, 16));
  return Buffer.concat([decipher.update(buf.subarray(16)), decipher.final()]).toString('utf8');
}

Verify

The fingerprints match on both sides, and decrypt(encrypt(x)) returns x.

Verify
node -e 'import("./crypto.mjs").then((m) => console.log(m.decrypt(m.encrypt("round trip ok"))))'

Confirmed by github.com

Did this fix it?

Cause 2 of 4

Hex or base64 ciphertext is turned back into the wrong bytes

You seeThe stored value contains only 0-9 and a-f while the code decodes it as base64 or utf8, or the other way round

Check

Ciphers work on raw bytes, so ciphertext saved as hex or base64 text has to be decoded with that same encoding before update(). Handing hex text to the decipher as utf8 feeds it twice as many wrong bytes, and final() reports bad decrypt. A quick pattern test shows how the value was stored.

Check
node -e 'const s = process.argv[1]; console.log(/^[0-9a-f]+$/i.test(s) ? "looks like hex" : /^[A-Za-z0-9+/]+=*$/.test(s) ? "looks like base64" : "neither", s.length)' "$CIPHERTEXT"

Fix

Name the input encoding in update() so Node.js converts the text back to bytes, and name the output encoding to get a string.

Fix
const text = decipher.update(ciphertextHex, 'hex', 'utf8') + decipher.final('utf8');

Verify

The call returns the original plain text and final() no longer throws.

Verify
node decrypt.js

Confirmed by github.com

Did this fix it?

Cause 3 of 4

Old records were written by the removed crypto.createCipher()

You seeThe writing code called crypto.createCipher(algorithm, password) with no IV, and the reader now uses createDecipheriv()

Check

createCipher() and createDecipher() were removed in Node.js 22.0.0. They made the key and IV from the password with OpenSSL's EVP_BytesToKey, using MD5, a single iteration and no salt. Passing that password through scrypt or a SHA hash yields other bytes, so every legacy record fails with bad decrypt.

Check
grep -rnE "createCipher\(|createDecipher\(" --exclude-dir=node_modules .

Fix

Rebuild the legacy key and IV once with the same MD5 steps, read the old data, then re-encrypt it with the scrypt and random IV scheme from cause 1.

Fix
import { createDecipheriv, createHash } from 'node:crypto';

// EVP_BytesToKey with MD5, one iteration, no salt (what createCipher used)
function legacyKeyIv(password, keyLen = 32, ivLen = 16) {
  let out = Buffer.alloc(0);
  let prev = Buffer.alloc(0);
  while (out.length < keyLen + ivLen) {
    prev = createHash('md5').update(Buffer.concat([prev, Buffer.from(password)])).digest();
    out = Buffer.concat([out, prev]);
  }
  return { key: out.subarray(0, keyLen), iv: out.subarray(keyLen, keyLen + ivLen) };
}

const { key, iv } = legacyKeyIv(process.env.OLD_PASSWORD);
const decipher = createDecipheriv('aes-256-cbc', key, iv);

Verify

An old record decrypts to readable text, and after re-encryption it reads back through the new code.

Verify
node migrate-legacy.mjs

Confirmed by nodejs.org

Did this fix it?

Cause 4 of 4

The other system encrypted without standard block padding

You seeWith padding off the text is readable, but the last block ends in 00 bytes or carries no padding at all

Check

By default decipher.final() looks for standard block padding and strips it. Data from another service set to zero padding or no padding decrypts fine but fails that check, which surfaces as bad decrypt.

Check
node -e 'const b = Buffer.from(process.argv[1], "hex"); console.log(b.at(-1) === 0 ? "ends in zero bytes" : "last byte " + b.at(-1))' "$LAST_BLOCK_HEX"

Fix

Call setAutoPadding(false) before final(), then remove the sender's own padding yourself.

Fix
const decipher = createDecipheriv('aes-256-cbc', key, iv).setAutoPadding(false);
const raw = Buffer.concat([decipher.update(data), decipher.final()]);
const text = raw.toString('utf8').replace(/\0+$/, ''); // sender padded with zero bytes

Verify

The text comes back without trailing NUL characters and no error is thrown.

Verify
node decrypt.js

Confirmed by nodejs.org

Did this fix it?

How do I stop it coming back?

  • Save the IV and salt inside the same stored value as the ciphertext, so no reader has to guess or regenerate them.
  • Keep one fixed sample record in the test suite and decrypt it in CI, which catches a changed key, salt or encoding before release.
  • Pick base64 or hex for stored ciphertext once and put the choice in the column or field name.
  • When another language encrypts the data, agree on mode, padding and IV layout in writing and test with a shared vector.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine on the same stack: TaxiDex, Workforce.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.