1
1
package com .thealgorithms .ciphers ;
2
2
3
- import java .util .HashMap ;
4
- import java .util .Map ;
5
-
6
3
/**
7
- * The Autokey Cipher is an interesting and historically significant encryption method,
8
- * as it improves upon the classic Vigenère Cipher by using the plaintext itself to
9
- * extend the key. This makes it harder to break using frequency analysis, as it
4
+ * The Autokey Cipher is an interesting and historically significant encryption method,
5
+ * as it improves upon the classic Vigenère Cipher by using the plaintext itself to
6
+ * extend the key. This makes it harder to break using frequency analysis, as it
10
7
* doesn’t rely solely on a repeated key.
11
8
* https://en.wikipedia.org/wiki/Autokey_cipher
12
- *
9
+ *
13
10
* @author bennybebo
14
11
*/
15
12
public class AutokeyCipher {
@@ -18,41 +15,41 @@ public class AutokeyCipher {
18
15
public String encrypt (String plaintext , String keyword ) {
19
16
plaintext = plaintext .toUpperCase ().replaceAll ("[^A-Z]" , "" ); // Sanitize input
20
17
keyword = keyword .toUpperCase ();
21
-
18
+
22
19
StringBuilder extendedKey = new StringBuilder (keyword );
23
20
extendedKey .append (plaintext ); // Extend key with plaintext
24
-
21
+
25
22
StringBuilder ciphertext = new StringBuilder ();
26
-
23
+
27
24
for (int i = 0 ; i < plaintext .length (); i ++) {
28
25
char plainChar = plaintext .charAt (i );
29
26
char keyChar = extendedKey .charAt (i );
30
-
27
+
31
28
int encryptedChar = ((plainChar - 'A' ) + (keyChar - 'A' )) % 26 + 'A' ;
32
29
ciphertext .append ((char ) encryptedChar );
33
30
}
34
-
31
+
35
32
return ciphertext .toString ();
36
33
}
37
34
38
35
// Decrypts the ciphertext using the Autokey cipher
39
36
public String decrypt (String ciphertext , String keyword ) {
40
37
ciphertext = ciphertext .toUpperCase ().replaceAll ("[^A-Z]" , "" ); // Sanitize input
41
38
keyword = keyword .toUpperCase ();
42
-
39
+
43
40
StringBuilder plaintext = new StringBuilder ();
44
41
StringBuilder extendedKey = new StringBuilder (keyword );
45
-
42
+
46
43
for (int i = 0 ; i < ciphertext .length (); i ++) {
47
44
char cipherChar = ciphertext .charAt (i );
48
45
char keyChar = extendedKey .charAt (i );
49
-
46
+
50
47
int decryptedChar = ((cipherChar - 'A' ) - (keyChar - 'A' ) + 26 ) % 26 + 'A' ;
51
48
plaintext .append ((char ) decryptedChar );
52
-
49
+
53
50
extendedKey .append ((char ) decryptedChar ); // Extend key with each decrypted char
54
51
}
55
-
52
+
56
53
return plaintext .toString ();
57
54
}
58
55
}
0 commit comments