-
Notifications
You must be signed in to change notification settings - Fork 0
/
AffineCipher.java
43 lines (38 loc) · 1.28 KB
/
AffineCipher.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
/**
* AffineCipher
*/
public class AffineCipher {
public static final String ABC = "abcdefghijklmnopqrstuvwxyz";
public static String encrypt(String TO_ENCRYPT, byte a, byte b) {
String encrypted = "";
for (byte i = 0; i < TO_ENCRYPT.length(); i++) {
String chr = String.valueOf(TO_ENCRYPT.charAt(i));
if (ABC.indexOf(chr) > -1)
encrypted += ABC.charAt((ABC.indexOf(chr) * a + b) % ABC.length());
else
encrypted += chr;
}
return encrypted;
}
public static String decrypt(String TO_ENCRYPT, byte a, byte b) {
int aInv = 0;
for (int i = 0; i < ABC.length(); i++) {
int flag = (a * i) % ABC.length();
if (flag == 1) {
aInv = i;
}
}
String decrypted = "";
for (int i = 0; i < TO_ENCRYPT.length(); i++) {
String chr = String.valueOf(TO_ENCRYPT.charAt(i));
if (ABC.indexOf(chr) > -1) {
int temp = aInv * (ABC.indexOf(chr) - b);
int mod = (temp % ABC.length() + ABC.length()) % ABC.length();
decrypted += ABC.charAt(mod);
} else {
decrypted += chr;
}
}
return decrypted;
}
}