Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions src/main/java/com/thealgorithms/ciphers/HillCipher.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
22 changes: 22 additions & 0 deletions src/test/java/com/thealgorithms/ciphers/HillCipherTest.java
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -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));
}
}
Loading