|
1 | 1 | package com.thealgorithms.ciphers; |
2 | 2 |
|
3 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; |
| 4 | +import static org.junit.jupiter.api.Assertions.assertThrows; |
4 | 5 |
|
5 | 6 | import org.junit.jupiter.api.Test; |
6 | 7 |
|
@@ -33,4 +34,25 @@ void hillCipherDecryptTest() { |
33 | 34 | // then |
34 | 35 | assertEquals("ACT", plainText); |
35 | 36 | } |
| 37 | + |
| 38 | + @Test |
| 39 | + void rejectsNonInvertibleKeyWithEvenDeterminant() { |
| 40 | + // det = 2, gcd(2, 26) = 2: passes the old zero-check but has no inverse mod 26 |
| 41 | + int[][] keyMatrix = {{1, 0}, {0, 2}}; |
| 42 | + assertThrows(IllegalArgumentException.class, () -> hillCipher.encrypt("AA", keyMatrix)); |
| 43 | + } |
| 44 | + |
| 45 | + @Test |
| 46 | + void rejectsNonInvertibleKeyWithDeterminantThirteen() { |
| 47 | + // det = 13, gcd(13, 26) = 13: also not invertible mod 26 |
| 48 | + int[][] keyMatrix = {{13, 0}, {0, 1}}; |
| 49 | + assertThrows(IllegalArgumentException.class, () -> hillCipher.encrypt("BB", keyMatrix)); |
| 50 | + } |
| 51 | + |
| 52 | + @Test |
| 53 | + void acceptsKeyWithNegativeCoprimeDeterminant() { |
| 54 | + // det = -1, coprime with 26: a valid key that a naive signed modulo would misclassify |
| 55 | + int[][] keyMatrix = {{1, 2}, {1, 1}}; |
| 56 | + assertEquals("XP", hillCipher.encrypt("HI", keyMatrix)); |
| 57 | + } |
36 | 58 | } |
0 commit comments