trekhleb/javascript-algorithms · error · Error

Invalid key string length. The key length must be a square o

Error message

Invalid key string length. The key length must be a square of message length

What it means

Error "Invalid key string length. The key length must be a square of message length" thrown in trekhleb/javascript-algorithms.

Source

Thrown at src/algorithms/cryptography/hill-cipher/hillCipher.js:71

  // keyString.length must equal to square of message.length
  if (keyMatrix.length !== message.length) {
    throw new Error('Invalid key string length. The key length must be a square of message length');
  }

View on GitHub (pinned to 85293e3e2b)

Solutions

  1. Choose a key whose matrix size (square root of the key length) equals the message length.
  2. Pad the message with filler letters (e.g. 'X') so its length matches the key matrix size.
  3. Pick a different key: for a message of length n the key length must be n^2.

When it happens

Trigger: hillCipherEncrypt is called with a key matrix size that does not match the message length (keyMatrix.length !== message.length), e.g. a 3x3 key from a 9-character keyString used with a 2-letter message.

Common situations: Encrypting a message whose length does not match the Hill cipher key matrix dimension, e.g. a 9-letter key (3 x 3 matrix) with a 5-letter message.


AI-assisted analysis of trekhleb/javascript-algorithms@85293e3e2b (2026-08-24). Data as JSON: /api/errors/f4cce33d271c83ea. Report an issue: GitHub.