Repository: TheAlgorithms/Java
Pull request #5569 (2024-10-04 18:34:28)

Add autokey cipher and tests
<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5569?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 54.05%. Comparing base [(`042d458`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/042d458d34043d54ae9331864a4c227b62a70355?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`5e86307`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/5e863070d511fe5f07d6a5ab0f641f1d401dd5cf?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5569      +/-   ##
============================================
+ Coverage     53.99%   54.05%   +0.05%     
- Complexity     3388     3393       +5     
============================================
  Files           535      536       +1     
  Lines         15429    15452      +23     
  Branches       2942     2944       +2     
============================================
+ Hits           8331     8352      +21     
- Misses         6747     6748       +1     
- Partials        351      352       +1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5569?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/src/main/java/com/thealgorithms/ciphers/Autokey.java b/src/main/java/com/thealgorithms/ciphers/Autokey.java
new file mode 100644
index 00000000..bb67f512
--- /dev/null
+++ b/src/main/java/com/thealgorithms/ciphers/Autokey.java
@@ -0,0 +1,55 @@
+package com.thealgorithms.ciphers;
+
+/**
+ * The Autokey Cipher is an interesting and historically significant encryption method,
+ * as it improves upon the classic Vigenère Cipher by using the plaintext itself to
+ * extend the key. This makes it harder to break using frequency analysis, as it
+ * doesn’t rely solely on a repeated key.
+ * https://en.wikipedia.org/wiki/Autokey_cipher
+ *
+ * @author bennybebo
+ */
+public class Autokey {
+
+    // Encrypts the plaintext using the Autokey cipher
+    public String encrypt(String plaintext, String keyword) {
+        plaintext = plaintext.toUpperCase().replaceAll("[^A-Z]", ""); // Sanitize input
+        keyword = keyword.toUpperCase();
+
+        StringBuilder extendedKey = new StringBuilder(keyword);
+        extendedKey.append(plaintext); // Extend key with plaintext
+
+        StringBuilder ciphertext = new StringBuilder();
+
+        for (int i = 0; i < plaintext.length(); i++) {
+            char plainChar = plaintext.charAt(i);
+            char keyChar = extendedKey.charAt(i);
+
+            int encryptedChar = (plainChar - 'A' + keyChar - 'A') % 26 + 'A';
+            ciphertext.append((char) encryptedChar);
+        }
+
+        return ciphertext.toString();
+    }
+
+    // Decrypts the ciphertext using the Autokey cipher
+    public String decrypt(String ciphertext, String keyword) {
+        ciphertext = ciphertext.toUpperCase().replaceAll("[^A-Z]", ""); // Sanitize input
+        keyword = keyword.toUpperCase();
+
+        StringBuilder plaintext = new StringBuilder();
+        StringBuilder extendedKey = new StringBuilder(keyword);
+
+        for (int i = 0; i < ciphertext.length(); i++) {
+            char cipherChar = ciphertext.charAt(i);
+            char keyChar = extendedKey.charAt(i);
+
+            int decryptedChar = (cipherChar - 'A' - (keyChar - 'A') + 26) % 26 + 'A';
+            plaintext.append((char) decryptedChar);
+
+            extendedKey.append((char) decryptedChar); // Extend key with each decrypted char
+        }
+
+        return plaintext.toString();
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/ciphers/AutokeyTest.java b/src/test/java/com/thealgorithms/ciphers/AutokeyTest.java
new file mode 100644
index 00000000..52ecff7c
--- /dev/null
+++ b/src/test/java/com/thealgorithms/ciphers/AutokeyTest.java
@@ -0,0 +1,36 @@
+package com.thealgorithms.ciphers;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+class AutokeyCipherTest {
+
+    Autokey autokeyCipher = new Autokey();
+
+    @Test
+    void autokeyEncryptTest() {
+        // given
+        String plaintext = "MEET AT DAWN";
+        String keyword = "QUEEN";
+
+        // when
+        String cipherText = autokeyCipher.encrypt(plaintext, keyword);
+
+        // then
+        assertEquals("CYIXNFHEPN", cipherText);
+    }
+
+    @Test
+    void autokeyDecryptTest() {
+        // given
+        String ciphertext = "CYIX NF HEPN";
+        String keyword = "QUEEN";
+
+        // when
+        String plainText = autokeyCipher.decrypt(ciphertext, keyword);
+
+        // then
+        assertEquals("MEETATDAWN", plainText);
+    }
+}