- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathSimpleSubCipher.java
85 lines (69 loc) · 2.76 KB
/
SimpleSubCipher.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
packagecom.thealgorithms.ciphers;
importjava.util.HashMap;
importjava.util.Map;
/**
* The simple substitution cipher is a cipher that has been in use for many
* hundreds of years (an excellent history is given in Simon Singhs 'the Code
* Book'). It basically consists of substituting every plaintext character for a
* different ciphertext character. It differs from the Caesar cipher in that the
* cipher alphabet is not simply the alphabet shifted, it is completely jumbled.
*/
publicclassSimpleSubCipher {
/**
* Encrypt text by replacing each element with its opposite character.
*
* @param message
* @param cipherSmall
* @return Encrypted message
*/
publicStringencode(Stringmessage, StringcipherSmall) {
StringBuilderencoded = newStringBuilder();
// This map is used to encode
Map<Character, Character> cipherMap = newHashMap<>();
charbeginSmallLetter = 'a';
charbeginCapitalLetter = 'A';
cipherSmall = cipherSmall.toLowerCase();
StringcipherCapital = cipherSmall.toUpperCase();
// To handle Small and Capital letters
for (inti = 0; i < cipherSmall.length(); i++) {
cipherMap.put(beginSmallLetter++, cipherSmall.charAt(i));
cipherMap.put(beginCapitalLetter++, cipherCapital.charAt(i));
}
for (inti = 0; i < message.length(); i++) {
if (Character.isAlphabetic(message.charAt(i))) {
encoded.append(cipherMap.get(message.charAt(i)));
} else {
encoded.append(message.charAt(i));
}
}
returnencoded.toString();
}
/**
* Decrypt message by replacing each element with its opposite character in
* cipher.
*
* @param encryptedMessage
* @param cipherSmall
* @return message
*/
publicStringdecode(StringencryptedMessage, StringcipherSmall) {
StringBuilderdecoded = newStringBuilder();
Map<Character, Character> cipherMap = newHashMap<>();
charbeginSmallLetter = 'a';
charbeginCapitalLetter = 'A';
cipherSmall = cipherSmall.toLowerCase();
StringcipherCapital = cipherSmall.toUpperCase();
for (inti = 0; i < cipherSmall.length(); i++) {
cipherMap.put(cipherSmall.charAt(i), beginSmallLetter++);
cipherMap.put(cipherCapital.charAt(i), beginCapitalLetter++);
}
for (inti = 0; i < encryptedMessage.length(); i++) {
if (Character.isAlphabetic(encryptedMessage.charAt(i))) {
decoded.append(cipherMap.get(encryptedMessage.charAt(i)));
} else {
decoded.append(encryptedMessage.charAt(i));
}
}
returndecoded.toString();
}
}