gchq/CyberChef · error · OperationError

Invalid IV length: ${iv.length} bytes SM4 uses an IV length

Error message

Invalid IV length: ${iv.length} bytes

SM4 uses an IV length of 16 bytes (128 bits).
Make sure you have specified the type correctly (e.g. Hex vs UTF8).

What it means

Thrown by SM4 Encrypt when the decoded IV is not 16 bytes and the mode does not start with 'ECB'. ECB and ECB/NoPadding skip this check; CBC, CFB, OFB, CTR, and CBC/NoPadding all require a 16-byte IV.

Source

Thrown at src/core/operations/SM4Encrypt.mjs:76

        ];
    }

    /**
     * @param {string} input
     * @param {Object[]} args
     * @returns {string}
     */
    run(input, args) {
        const key = Utils.convertToByteArray(args[0].string, args[0].option),
            iv = Utils.convertToByteArray(args[1].string, args[1].option),
            [,, mode, inputType, outputType] = args;

        if (key.length !== 16)
            throw new OperationError(`Invalid key length: ${key.length} bytes

SM4 uses a key length of 16 bytes (128 bits).`);
        if (iv.length !== 16 && !mode.startsWith("ECB"))
            throw new OperationError(`Invalid IV length: ${iv.length} bytes

SM4 uses an IV length of 16 bytes (128 bits).
Make sure you have specified the type correctly (e.g. Hex vs UTF8).`);

        input = Utils.convertToByteArray(input, inputType);
        const output = encryptSM4(input, key, iv, mode.substring(0, 3), mode.endsWith("NoPadding"));
        return outputType === "Hex" ? toHex(output) : Utils.byteArrayToUtf8(output);
    }

}

export default SM4Encrypt;

View on GitHub (pinned to 4290ea7539)

Solutions

  1. Supply a 16-byte IV for non-ECB modes; set the toggle correctly (Hex for hex IVs).
  2. Use an ECB mode if no IV is intended.
  3. Verify IV toggle matches IV encoding.

Example fix

// before
sm4Encrypt.run(pt, [keyArg, {string:"", option:"Hex"}, "CBC", ...])
// after
sm4Encrypt.run(pt, [keyArg, {string:"00112233445566778899aabbccddeeff", option:"Hex"}, "CBC", ...])
Defensive patterns

Strategy: validation

Validate before calling

const iv = Utils.convertToByteArray(ivArg.string, ivArg.option);
if (!String(mode).startsWith("ECB") && iv.length !== 16) {
  throw new Error(`IV must be 16 bytes for ${mode}, got ${iv.length}`);
}

Type guard

function isSm4IvValid(ivArg, mode) {
  if (String(mode).startsWith("ECB")) return true;
  return Utils.convertToByteArray(ivArg.string, ivArg.option).length === 16;
}

Prevention

When it happens

Trigger: A non-ECB mode combined with an IV whose decoded length is not 16, or an empty IV field. Toggle mismatch (hex IV read as UTF8) is the most frequent cause.

Common situations: Forgetting the IV for CBC encryption; wrong toggle on the IV; reusing an IV from a different cipher; CBC/NoPadding mode still needing an IV.

Related errors


AI-assisted analysis of gchq/CyberChef@4290ea7539 (2026-08-13). Data as JSON: /api/errors/5e4e627deba6fac0. Report an issue: GitHub.