Repository navigation
Expand file tree
/
Copy pathCrypto.java
More file actions
74 lines (58 loc) · 2.09 KB
/
Copy pathCrypto.java
File metadata and controls
74 lines (58 loc) · 2.09 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
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
import java.util.ArrayList;
import java.util.List;
public class Crypto {
private String normalizedPlaintext;
private int squareSize;
public Crypto(String text) {
this.normalizedPlaintext = normalizeText(text);
this.squareSize = calculateSquareSize(normalizedPlaintext);
}
public String getNormalizedPlaintext() {
return normalizedPlaintext;
}
public int getSquareSize() {
return squareSize;
}
private static String normalizeText(String text) {
return text.toLowerCase().codePoints()
.filter(x -> Character.isLetterOrDigit(x))
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
}
private static int calculateSquareSize(String text) {
return (int) Math.ceil(Math.sqrt(text.length()));
}
public List<String> getPlaintextSegments() {
return getSegmentText(normalizedPlaintext, squareSize);
}
private static List<String> getSegmentText(String text, int squareSize) {
List<String> segments = new ArrayList<>();
int index = 0;
while (index < text.length()) {
if (index + squareSize < text.length()) {
segments.add(text.substring(index, index + squareSize));
} else {
segments.add(text.substring(index));
}
index += squareSize;
}
return segments;
}
public String getCipherText() {
return getNormalizedCipherText().replaceAll("\\s", "");
}
public String getNormalizedCipherText() {
StringBuilder cipherText = new StringBuilder(normalizedPlaintext.length());
for (int index = 0; index < squareSize; index++) {
for (String segment : getPlaintextSegments()) {
if (index < segment.length()) {
cipherText.append(segment.charAt(index));
}
}
if (index < squareSize - 1) {
cipherText.append(" ");
}
}
return cipherText.toString();
}
}