Jared Norris 6 anni fa
parent
commit
b3de406b05
1 ha cambiato i file con 8 aggiunte e 19 eliminazioni
  1. 8
    19
      Crypto/src/ROT13.java

+ 8
- 19
Crypto/src/ROT13.java Vedi File

1
-import java.util.*;
2
-
3
 public class ROT13  {
1
 public class ROT13  {
4
-    private int shift;
5
-    private Map<Character, Character> cypher = new HashMap<>();
2
+    private String cryptKey;
3
+    private String alphabet = "abcdefghijklmnopqrstuvwxyz";
4
+
6
 
5
 
7
     ROT13(Character cs, Character cf) {
6
     ROT13(Character cs, Character cf) {
8
-        shift = Math.abs((int)cs - (int)cf);
9
-        setupHM();
7
+        int index = Math.abs((int)cs - (int)cf);
8
+        cryptKey = rotate(alphabet, alphabet.charAt(index));
10
     }
9
     }
11
 
10
 
12
-    ROT13(){}
13
-
14
-    public void setupHM() {
15
-        String alphabet = "abcdefghijklmnopqrstuvwxyz";
16
-
17
-        for(Character c : alphabet.toCharArray()) {
18
-            int offset = (int)c + shift > 122 ? (int)c - shift : (int)c  + shift;
19
-            cypher.put(c, (char)offset);
20
-        }
21
-    }
11
+    ROT13(){ cryptKey = rotate(alphabet, 'n'); }
22
 
12
 
23
     public String crypt(String text) throws UnsupportedOperationException {
13
     public String crypt(String text) throws UnsupportedOperationException {
24
         StringBuilder result = new StringBuilder();
14
         StringBuilder result = new StringBuilder();
26
         for(Character c : text.toCharArray()) {
16
         for(Character c : text.toCharArray()) {
27
             if (Character.isLetter(c)) {
17
             if (Character.isLetter(c)) {
28
                 if (Character.isUpperCase(c)) {
18
                 if (Character.isUpperCase(c)) {
29
-                    result.append(Character.toUpperCase(cypher.get(Character.toLowerCase(c))));
19
+                    result.append(Character.toUpperCase(cryptKey.charAt(alphabet.indexOf(Character.toLowerCase(c)))));
30
                 }
20
                 }
31
-                else result.append(cypher.get(c));
21
+                else result.append(cryptKey.charAt(alphabet.indexOf(c)));
32
             }
22
             }
33
             else result.append(c);
23
             else result.append(c);
34
         }
24
         }
46
     public static String rotate(String s, Character c) {
36
     public static String rotate(String s, Character c) {
47
         return s.substring(s.indexOf(c)) + s.substring(0, s.indexOf(c));
37
         return s.substring(s.indexOf(c)) + s.substring(0, s.indexOf(c));
48
     }
38
     }
49
-
50
 }
39
 }