|
| 1 | +package com.thealgorithms.ciphers; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +/** |
| 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 |
| 10 | + * doesn’t rely solely on a repeated key. |
| 11 | + * |
| 12 | + * @author bennybebo |
| 13 | + */ |
| 14 | +public class AutokeyCipher { |
| 15 | + |
| 16 | + // Encrypts the plaintext using the Autokey cipher |
| 17 | + public String encrypt(String plaintext, String keyword) { |
| 18 | + plaintext = plaintext.toUpperCase().replaceAll("[^A-Z]", ""); // Sanitize input |
| 19 | + keyword = keyword.toUpperCase(); |
| 20 | + |
| 21 | + StringBuilder extendedKey = new StringBuilder(keyword); |
| 22 | + extendedKey.append(plaintext); // Extend key with plaintext |
| 23 | + |
| 24 | + StringBuilder ciphertext = new StringBuilder(); |
| 25 | + |
| 26 | + for (int i = 0; i < plaintext.length(); i++) { |
| 27 | + char plainChar = plaintext.charAt(i); |
| 28 | + char keyChar = extendedKey.charAt(i); |
| 29 | + |
| 30 | + int encryptedChar = ((plainChar - 'A') + (keyChar - 'A')) % 26 + 'A'; |
| 31 | + ciphertext.append((char) encryptedChar); |
| 32 | + } |
| 33 | + |
| 34 | + return ciphertext.toString(); |
| 35 | + } |
| 36 | + |
| 37 | + // Decrypts the ciphertext using the Autokey cipher |
| 38 | + public String decrypt(String ciphertext, String keyword) { |
| 39 | + ciphertext = ciphertext.toUpperCase().replaceAll("[^A-Z]", ""); // Sanitize input |
| 40 | + keyword = keyword.toUpperCase(); |
| 41 | + |
| 42 | + StringBuilder plaintext = new StringBuilder(); |
| 43 | + StringBuilder extendedKey = new StringBuilder(keyword); |
| 44 | + |
| 45 | + for (int i = 0; i < ciphertext.length(); i++) { |
| 46 | + char cipherChar = ciphertext.charAt(i); |
| 47 | + char keyChar = extendedKey.charAt(i); |
| 48 | + |
| 49 | + int decryptedChar = ((cipherChar - 'A') - (keyChar - 'A') + 26) % 26 + 'A'; |
| 50 | + plaintext.append((char) decryptedChar); |
| 51 | + |
| 52 | + extendedKey.append((char) decryptedChar); // Extend key with each decrypted char |
| 53 | + } |
| 54 | + |
| 55 | + return plaintext.toString(); |
| 56 | + } |
| 57 | +} |
0 commit comments