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
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand Down
26 changes: 26 additions & 0 deletions src/test/java/com/thealgorithms/ciphers/PlayfairTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
}
}
Loading