TheAlgorithms/Python · error · ValueError

determinant modular {req_l} of encryption key({det}) is not

Error message

determinant modular {req_l} of encryption key({det}) is not co prime w.r.t {req_l}.
Try another key.

What it means

Raised by HillCipher's key validation (ciphers/hill_cipher.py) when det(encrypt_key) is not coprime with the alphabet length (len(key_string), 85 for the default charset). The matrix inverse needed for decryption only exists mod L when gcd(det, L) == 1, so such a key cannot decrypt anything it encrypts.

Source

Thrown at ciphers/hill_cipher.py:102

        return self.key_string[int(num)]

    def check_determinant(self) -> None:
        """
        >>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]]))
        >>> hill_cipher.check_determinant()
        """
        det = round(np.linalg.det(self.encrypt_key))

        if det < 0:
            det = det % len(self.key_string)

        req_l = len(self.key_string)
        if greatest_common_divisor(det, len(self.key_string)) != 1:
            msg = (
                f"determinant modular {req_l} of encryption key({det}) "
                f"is not co prime w.r.t {req_l}.\nTry another key."
            )
            raise ValueError(msg)

    def process_text(self, text: str) -> str:
        """
        >>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]]))
        >>> hill_cipher.process_text('Testing Hill Cipher')
        'TESTINGHILLCIPHERR'
        >>> hill_cipher.process_text('hello')
        'HELLOO'
        """
        chars = [char for char in text.upper() if char in self.key_string]

        last = chars[-1]
        while len(chars) % self.break_key != 0:
            chars.append(last)

        return "".join(chars)

    def encrypt(self, text: str) -> str:

View on GitHub (pinned to f5988cc097)

Solutions

  1. Try a different key matrix, e.g. the doctest-valid [[2, 5], [1, 6]] (det 7, coprime with 85)
  2. Generate random integer matrices and retry until gcd(round(det), 85) == 1
  3. For custom key_string of length L, enforce gcd(det, L) == 1 in your key generator

Example fix

# before
key = np.array([[2, 4], [4, 8]])  # det = 0
hc = HillCipher(key)

# after
import numpy as np
from maths.greatest_common_divisor import gcd_by_iterative as gcd
while True:
    key = np.random.randint(0, 85, (2, 2))
    det = round(np.linalg.det(key))
    if gcd(det, 85) == 1:
        break
hc = HillCipher(key)
Defensive patterns

Strategy: retry

Validate before calling

import numpy as np
from maths.greatest_common_divisor import gcd_by_iterative as gcd
L = 85  # default key_string length
det = round(np.linalg.det(key))
assert gcd(det, L) == 1, f'key determinant {det} not coprime with {L}'

Try / catch

while True:
    key = np.random.randint(0, 85, (n, n))
    det = round(np.linalg.det(key))
    if gcd(det, 85) == 1:
        break
hc = HillCipher(key)

Prevention

When it happens

Trigger: HillCipher(np.array([[2, 4], [4, 8]])) — det 0; any integer matrix whose determinant shares a factor with 85 (5 or 17); random key matrices that fail the coprimality test with probability ~1 - phi(85)/85.

Common situations: Generating random keys without re-checking the determinant; scaling a valid key by an integer (multiplies det, usually breaks coprimality); switching alphabet/key_string without re-validating keys.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/f562d998281c731c. Report an issue: GitHub.