-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShiftCryptoSystem.java
More file actions
45 lines (38 loc) · 1.38 KB
/
Copy pathShiftCryptoSystem.java
File metadata and controls
45 lines (38 loc) · 1.38 KB
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
package project1;
import java.util.Random;
public class ShiftCryptoSystem {
private int key;
public static int additive(int a, int m) {
int normalised = ((a % m) + m) % m;
return (m - normalised) % m;
}
public static String encrypt(String plaintext, int key) {
// if key is greater than 26 then the shift is moduled
key = (key % 26) % 26;
StringBuilder sb = new StringBuilder();
for (char c : plaintext.toCharArray()) {
// clean while encrypting (we just shift alphabetical chars)
if (Character.isLetter(c)) {
char base = Character.isUpperCase(c) ? 'A' : 'a';
sb.append((char)(base + (c - base + key) % 26));
} else {
sb.append(c);
}
}
return sb.toString();
}
public static String decrypt(String ciphertext, int key) {
// Decryption in shift cipher is the same as encrypting
// but shifts backwards
return encrypt(ciphertext, additive(key, 26));
}
public static String[] bruteForce(String ciphertext) {
// try all shifts to decrypt the cipher
String[] results = new String[26];
for (int key = 0; key < 26; key++) {
// store current attempt of decrypting
results[key] = decrypt(ciphertext, key);
}
return results;
}
}