-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncodeDecodeRunner.java
More file actions
85 lines (71 loc) · 2.55 KB
/
EncodeDecodeRunner.java
File metadata and controls
85 lines (71 loc) · 2.55 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
75
76
77
78
79
80
81
82
83
84
85
import java.io.*;
import java.util.concurrent.ThreadLocalRandom;
public class EncodeDecodeRunner {
private static final String HASH_STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789()*+,-./";
public EncodeDecodeRunner() {
}
/**
* Encodes the unencoded string from user
*
* @param toUnencode
* @param sb
* @return encodedString
*/
public String encode(String toUnencode, StringBuilder sb) {
int min = 0;
int max = 43;
int offSetIndex = ThreadLocalRandom.current().nextInt(min, max + 1);
String offsetChar = String.valueOf(HASH_STR.charAt(offSetIndex));
sb.append(offsetChar);
char[] uncodedCharArr = toUnencode.toCharArray();
for (char currChar : uncodedCharArr) {
if (currChar == ' ') {
sb.append(' ');
} else {
String currCharStringVal = String.valueOf(currChar);
int currCharIdx = HASH_STR.indexOf(currCharStringVal.toUpperCase());
if (currCharIdx == -1) {
sb.append(currCharStringVal);
} else {
currCharIdx += offSetIndex;
if (currCharIdx > 43) {
currCharIdx = currCharIdx % 43;
}
sb.append(String.valueOf(HASH_STR.charAt(currCharIdx)));
}
}
}
return sb.toString();
}
/**
* Decodes an encoded string from user
*
* @param toDecode
* @param sb
* @return decodedString
*/
public String decode(String toDecode, StringBuilder sb) {
String decodeVal = String.valueOf(toDecode.charAt(0));
toDecode = toDecode.substring(1);
int offSetIndex = HASH_STR.indexOf(decodeVal);
char[] toDecodeCharArr = toDecode.toCharArray();
for (char currChar : toDecodeCharArr) {
if (currChar == ' ') {
sb.append(' ');
} else {
String currCharStringVal = String.valueOf(currChar);
int currCharIdx = HASH_STR.indexOf(currCharStringVal.toUpperCase());
if (currCharIdx == -1) {
sb.append(currCharStringVal);
} else {
currCharIdx -= offSetIndex;
if (currCharIdx < 0) {
currCharIdx = 43 + currCharIdx;
}
sb.append(String.valueOf(HASH_STR.charAt(currCharIdx)));
}
}
}
return sb.toString();
}
}