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