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