|
| 1 | +package com.thealgorithms.ciphers; |
| 2 | + |
| 3 | +/** |
| 4 | + * The Atbash cipher is a simple substitution cipher that replaces each letter |
| 5 | + * in the alphabet with its reverse. |
| 6 | + * For example, 'A' becomes 'Z', 'B' becomes 'Y', and so on. It works |
| 7 | + * identically for both uppercase and lowercase letters. |
| 8 | + * It's a symmetric cipher, meaning applying it twice returns the original text. |
| 9 | + * Hence, the encrypting and the decrypting functions are identical |
| 10 | + * @author https://github.com/Krounosity |
| 11 | + * Learn more: https://en.wikipedia.org/wiki/Atbash |
| 12 | + */ |
| 13 | + |
| 14 | +public class AtbashCipher { |
| 15 | + |
| 16 | + private String toConvert; |
| 17 | + |
| 18 | + // Default constructor. |
| 19 | + AtbashCipher() { |
| 20 | + } |
| 21 | + |
| 22 | + // String setting constructor. |
| 23 | + AtbashCipher(String str) { |
| 24 | + toConvert = str; |
| 25 | + } |
| 26 | + |
| 27 | + // String getter method. |
| 28 | + public String getString() { |
| 29 | + return toConvert; |
| 30 | + } |
| 31 | + |
| 32 | + // String setter method. |
| 33 | + public void setString(String str) { |
| 34 | + toConvert = str; |
| 35 | + } |
| 36 | + |
| 37 | + // Checking whether the current character is capital. |
| 38 | + private boolean isCapital(char ch) { |
| 39 | + return ch >= 'A' && ch <= 'Z'; |
| 40 | + } |
| 41 | + |
| 42 | + // Checking whether the current character is smallcased. |
| 43 | + private boolean isSmall(char ch) { |
| 44 | + return ch >= 'a' && ch <= 'z'; |
| 45 | + } |
| 46 | + |
| 47 | + // Converting text to atbash cipher code or vice versa. |
| 48 | + public String convert() { |
| 49 | + |
| 50 | + // Using StringBuilder to store new string. |
| 51 | + StringBuilder convertedString = new StringBuilder(); |
| 52 | + |
| 53 | + // Iterating for each character. |
| 54 | + for (char ch : toConvert.toCharArray()) { |
| 55 | + |
| 56 | + // If the character is smallcased. |
| 57 | + if (isSmall(ch)) { |
| 58 | + convertedString.append((char) ('z' - (ch - 'a'))); |
| 59 | + } |
| 60 | + // If the character is capital cased. |
| 61 | + else if (isCapital(ch)) { |
| 62 | + convertedString.append((char) ('Z' - (ch - 'A'))); |
| 63 | + } |
| 64 | + // Non-alphabetical character. |
| 65 | + else { |
| 66 | + convertedString.append(ch); |
| 67 | + } |
| 68 | + } |
| 69 | + return convertedString.toString(); |
| 70 | + } |
| 71 | +} |
0 commit comments