diff --git a/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java b/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java index 76ceb6dbce31..3e29ea489dd8 100644 --- a/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java @@ -6,7 +6,11 @@ public class PlayfairCipher { private String key; public PlayfairCipher(String key) { - this.key = key; + // Normalize the key the same way the plaintext is normalized in encrypt(): + // uppercase, J folded into I, and non-letters removed. Without this a + // lowercase or mixed-case key, a key containing J, or a key with + // punctuation silently produces a wrong matrix. + this.key = key.toUpperCase().replace("J", "I").replaceAll("[^A-Z]", ""); generateMatrix(); } diff --git a/src/test/java/com/thealgorithms/ciphers/PlayfairTest.java b/src/test/java/com/thealgorithms/ciphers/PlayfairTest.java index fa497e4682e8..2386aa735b7e 100644 --- a/src/test/java/com/thealgorithms/ciphers/PlayfairTest.java +++ b/src/test/java/com/thealgorithms/ciphers/PlayfairTest.java @@ -34,4 +34,30 @@ public void testEncryptionAndDecryption() { assertEquals(plaintext, decryptedText); } + + @Test + public void testLowercaseKeyBehavesLikeUppercase() { + PlayfairCipher lowercase = new PlayfairCipher("monarchy"); + PlayfairCipher uppercase = new PlayfairCipher("MONARCHY"); + + assertEquals(uppercase.encrypt("HELLO"), lowercase.encrypt("HELLO")); + assertEquals("CFSUPM", lowercase.encrypt("HELLO")); + } + + @Test + public void testKeyContainingJStillCoversZ() { + PlayfairCipher playfairCipher = new PlayfairCipher("JUMP"); + + String decryptedText = playfairCipher.decrypt(playfairCipher.encrypt("ZOO")); + + assertEquals("ZOXO", decryptedText); + } + + @Test + public void testKeyWithNonLettersIsStripped() { + PlayfairCipher messy = new PlayfairCipher("Mon@rchy2026"); + PlayfairCipher clean = new PlayfairCipher("MONRCHY"); + + assertEquals(clean.encrypt("HELLO"), messy.encrypt("HELLO")); + } }