Skip to content

Commit 9870de2

Browse files
Aditya2375alxkm
andauthored
fix: normalize Playfair key before building the matrix (#7779)
* fix: normalize Playfair key before building the matrix encrypt() normalizes the plaintext (uppercase, J folded into I, non-letters stripped) but the constructor passed the raw key straight into the matrix builder. A lowercase key like "monarchy" or one containing J or punctuation produced a wrong matrix, so ciphertext was garbage and Z could never round-trip. Normalize the key the same way before building the matrix. * test: cover Playfair keys that are lowercase, contain J, or have non-letters Regression tests for the key-normalization fix: a lowercase key must behave like its uppercase form, a key containing J must still cover Z in the matrix, and punctuation or digits in the key must be ignored. --------- Co-authored-by: Oleksandr <19151554+alxkm@users.noreply.github.com>
1 parent 54d056d commit 9870de2

2 files changed

Lines changed: 31 additions & 1 deletion

File tree

‎src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,11 @@ public class PlayfairCipher {
66
private String key;
77

88
public PlayfairCipher(String key) {
9-
this.key = key;
9+
// Normalize the key the same way the plaintext is normalized in encrypt():
10+
// uppercase, J folded into I, and non-letters removed. Without this a
11+
// lowercase or mixed-case key, a key containing J, or a key with
12+
// punctuation silently produces a wrong matrix.
13+
this.key = key.toUpperCase().replace("J", "I").replaceAll("[^A-Z]", "");
1014
generateMatrix();
1115
}
1216

‎src/test/java/com/thealgorithms/ciphers/PlayfairTest.java‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,4 +34,30 @@ public void testEncryptionAndDecryption() {
3434

3535
assertEquals(plaintext, decryptedText);
3636
}
37+
38+
@Test
39+
public void testLowercaseKeyBehavesLikeUppercase() {
40+
PlayfairCipher lowercase = new PlayfairCipher("monarchy");
41+
PlayfairCipher uppercase = new PlayfairCipher("MONARCHY");
42+
43+
assertEquals(uppercase.encrypt("HELLO"), lowercase.encrypt("HELLO"));
44+
assertEquals("CFSUPM", lowercase.encrypt("HELLO"));
45+
}
46+
47+
@Test
48+
public void testKeyContainingJStillCoversZ() {
49+
PlayfairCipher playfairCipher = new PlayfairCipher("JUMP");
50+
51+
String decryptedText = playfairCipher.decrypt(playfairCipher.encrypt("ZOO"));
52+
53+
assertEquals("ZOXO", decryptedText);
54+
}
55+
56+
@Test
57+
public void testKeyWithNonLettersIsStripped() {
58+
PlayfairCipher messy = new PlayfairCipher("Mon@rchy2026");
59+
PlayfairCipher clean = new PlayfairCipher("MONRCHY");
60+
61+
assertEquals(clean.encrypt("HELLO"), messy.encrypt("HELLO"));
62+
}
3763
}

0 commit comments

Comments
 (0)