trekhleb/javascript-algorithms · error · Error

Invalid key string length. The square root of the key string

Error message

Invalid key string length. The square root of the key string must be an integer

What it means

Error "Invalid key string length. The square root of the key string must be an integer" thrown in trekhleb/javascript-algorithms.

Source

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

const generateKeyMatrix = (keyString) => {
  const matrixSize = Math.sqrt(keyString.length);
  if (!Number.isInteger(matrixSize)) {
    throw new Error(
      'Invalid key string length. The square root of the key string must be an integer',
    );
  }}

View on GitHub (pinned to 85293e3e2b)

Solutions

  1. Pass a keyString whose length is a perfect square (4, 9, 16, 25, ...) so it can fill an n x n key matrix.
  2. Pad or trim the key to the nearest perfect-square length before calling hillCipherEncrypt.
  3. Validate the key up front with Number.isInteger(Math.sqrt(keyString.length)) and reject invalid keys with a clear message.

When it happens

Trigger: hillCipherEncrypt is called with a keyString whose length is not a perfect square (e.g. 5 or 10 characters), so Math.sqrt(keyString.length) is not an integer and no square key matrix can be generated.

Common situations: Calling hillCipherEncrypt with a key that cannot form a square matrix; the Hill cipher needs an n x n key matrix, so the key length must be n^2.


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