diff --git a/src/main/java/com/thealgorithms/ciphers/HillCipher.java b/src/main/java/com/thealgorithms/ciphers/HillCipher.java index 01b1aeb8bc6c..db86340aa3cf 100644 --- a/src/main/java/com/thealgorithms/ciphers/HillCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/HillCipher.java @@ -68,14 +68,22 @@ public String decrypt(String message, int[][] inverseKeyMatrix) { return plainText.toString(); } - // Validates that the determinant of the key matrix is not zero modulo 26 + // Validates that the key matrix is invertible modulo 26, which requires the + // determinant to be coprime with 26. Checking only for a zero determinant is not + // enough: a determinant of 2 or 13 (or any other non-unit) passes that check but + // has no inverse, so encryption collapses distinct plaintexts onto the same + // ciphertext and decryption becomes impossible. private void validateDeterminant(int[][] keyMatrix, int n) { - int det = determinant(keyMatrix, n) % 26; - if (det == 0) { - throw new IllegalArgumentException("Invalid key matrix. Determinant is zero modulo 26."); + int det = Math.floorMod(determinant(keyMatrix, n), 26); + if (gcd(det, 26) != 1) { + throw new IllegalArgumentException("Invalid key matrix. Determinant must be coprime with 26 to be invertible modulo 26."); } } + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } + // Computes the determinant of a matrix recursively private int determinant(int[][] matrix, int n) { int det = 0; diff --git a/src/test/java/com/thealgorithms/ciphers/HillCipherTest.java b/src/test/java/com/thealgorithms/ciphers/HillCipherTest.java index 8121b6177aa9..3f8b81c0d069 100644 --- a/src/test/java/com/thealgorithms/ciphers/HillCipherTest.java +++ b/src/test/java/com/thealgorithms/ciphers/HillCipherTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.ciphers; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; @@ -33,4 +34,25 @@ void hillCipherDecryptTest() { // then assertEquals("ACT", plainText); } + + @Test + void rejectsNonInvertibleKeyWithEvenDeterminant() { + // det = 2, gcd(2, 26) = 2: passes the old zero-check but has no inverse mod 26 + int[][] keyMatrix = {{1, 0}, {0, 2}}; + assertThrows(IllegalArgumentException.class, () -> hillCipher.encrypt("AA", keyMatrix)); + } + + @Test + void rejectsNonInvertibleKeyWithDeterminantThirteen() { + // det = 13, gcd(13, 26) = 13: also not invertible mod 26 + int[][] keyMatrix = {{13, 0}, {0, 1}}; + assertThrows(IllegalArgumentException.class, () -> hillCipher.encrypt("BB", keyMatrix)); + } + + @Test + void acceptsKeyWithNegativeCoprimeDeterminant() { + // det = -1, coprime with 26: a valid key that a naive signed modulo would misclassify + int[][] keyMatrix = {{1, 2}, {1, 1}}; + assertEquals("XP", hillCipher.encrypt("HI", keyMatrix)); + } }