瀏覽代碼

finished ROT13. Need to fix my own cipher

thulasi 7 年之前
父節點
當前提交
d2920a9f87
共有 7 個文件被更改,包括 314 次插入13 次删除
  1. 71
    0
      Crypto/src/NewCipher.java
  2. 27
    0
      Crypto/src/NewCipherTest.java
  3. 131
    6
      Crypto/src/ROT13.java
  4. 30
    7
      Crypto/src/ROT13Test.java
  5. 15
    0
      SimpleCrypt.iml
  6. 14
    0
      encryptedFile.txt
  7. 26
    0
      pom.xml

+ 71
- 0
Crypto/src/NewCipher.java 查看文件

@@ -0,0 +1,71 @@
1
+public class NewCipher {
2
+    String text;
3
+    String encryptedText;
4
+    String alphabets;
5
+    int key;
6
+
7
+    public NewCipher(String text, int key) {
8
+        this.text = text;
9
+        this.key = key;
10
+        alphabets = "abcdefghijklmnopqrstuvwxyz";
11
+    }
12
+
13
+    public String encrypt(){
14
+
15
+        String encrypted = "";
16
+//        for (int i = 0; i < text.length(); i++) {
17
+//            char ch = text.charAt(i);
18
+//            if (Character.isLetter(ch)) {
19
+//                if(ch+key >='a' && ch+key <= 'z') {
20
+//                    ch = (char)(ch + key);
21
+//                }
22
+//                else
23
+//                {
24
+//                   int index = alphabets.indexOf(ch);
25
+//                   for()
26
+//
27
+//                }
28
+//            }
29
+//
30
+//            encrypted += ch;
31
+//        }
32
+
33
+        for(int i = 0; i<text.length(); i++){
34
+            char ch = text.charAt(i);
35
+            if(Character.isLetter(ch)){
36
+                if(ch+key >='a' && ch+key <= 'z') {
37
+                    ch = (char)(ch + key);
38
+                }
39
+                else {
40
+                    int pos = alphabets.indexOf(ch);
41
+                    int times = 0;
42
+                    int j;
43
+                    for(j = pos; times <key; j++) {
44
+                        if(j==alphabets.length()){
45
+                            j= 0;
46
+                        }
47
+                        times++;
48
+                    }
49
+                    ch = alphabets.charAt(j);
50
+                }
51
+            }
52
+            encrypted += ch;
53
+        }
54
+        System.out.println("encrypted text is " + encrypted);
55
+        return encrypted;
56
+    }
57
+
58
+    public String decrypt(){
59
+        String decrypted = "";
60
+        for (int i = 0; i < text.length(); i++) {
61
+            char ch = text.charAt(i);
62
+            if (Character.isLetter(ch)) {
63
+                ch = (char)(((ch - 'a') - key) % 26 + 'a');
64
+            }
65
+
66
+            decrypted += ch;
67
+        }
68
+        System.out.println("decrypted text is " + decrypted);
69
+        return decrypted;
70
+    }
71
+}

+ 27
- 0
Crypto/src/NewCipherTest.java 查看文件

@@ -0,0 +1,27 @@
1
+import org.junit.Assert;
2
+import org.junit.Before;
3
+import org.junit.Test;
4
+
5
+public class NewCipherTest {
6
+    NewCipher cipher;
7
+
8
+    @Before
9
+    public void setup(){
10
+        cipher = new NewCipher("abc jkl wxyz", 2);
11
+    }
12
+
13
+    @Test
14
+    public void testEncrypt(){
15
+        String expected = "cde lmn yzab";
16
+        String actual = cipher.encrypt();
17
+        Assert.assertEquals(expected, actual);
18
+    }
19
+
20
+    @Test
21
+    public void testDecrypt(){
22
+        String expected = cipher.text;
23
+        cipher.encrypt();
24
+        String actual = cipher.decrypt();
25
+        Assert.assertEquals(expected, actual);
26
+    }
27
+}

+ 131
- 6
Crypto/src/ROT13.java 查看文件

@@ -1,32 +1,157 @@
1
+import java.io.*;
2
+
1 3
 import static java.lang.Character.isLowerCase;
2 4
 import static java.lang.Character.isUpperCase;
3 5
 import static java.lang.Character.toLowerCase;
4 6
 
5 7
 public class ROT13  {
6 8
 
9
+    int shift;
7 10
     ROT13(Character cs, Character cf) {
11
+        shift = cf - cs;
8 12
     }
9 13
 
10 14
     ROT13() {
11 15
     }
12 16
 
13
-
14 17
     public String crypt(String text) throws UnsupportedOperationException {
15
-
16
-        return "";
18
+        StringBuilder sb = new StringBuilder();
19
+        for(int i=0;i<text.length();i++){
20
+            if((text.charAt(i) >= 'a' && text.charAt(i) <= 'm') || (text.charAt(i) >= 'A' && text.charAt(i) <= 'M')){
21
+                sb.append((char)(text.charAt(i) + 13));
22
+            }
23
+            else if((text.charAt(i) >= 'n' && text.charAt(i) <= 'z') || (text.charAt(i) >= 'N' && text.charAt(i) <= 'Z')){
24
+                sb.append((char)(text.charAt(i) - 13));
25
+            }
26
+            else
27
+                sb.append(text.charAt(i));
28
+        }
29
+        return sb.toString();
17 30
     }
18 31
 
19 32
     public String encrypt(String text) {
20
-        return text;
33
+        String encrypted = "";
34
+        //Individual characters of a String are numbered from 0 until n-1 where n is the
35
+        //length of the string
36
+        //So what we want to repeat is "get the i character of the String, encrypt it, and build
37
+        //it onto the String named encrypted" We want to do that for each value of i
38
+        //To actually encrypt, we need to worry about "wraparound" issues around z
39
+        for (int i = 0; i < text.length(); i++) {
40
+            //Check if it is a letter. If it isn't, then we don't have to do anything anyway
41
+            if( (text.charAt(i) >= 'A' && text.charAt(i) <= 'Z') ||
42
+                    (text.charAt(i) >= 'a' && text.charAt(i) <= 'z'))
43
+            {
44
+                //Check if there was "wraparound" For example z + 3 should give us c
45
+                //In this case, the way to get this result is by subtracting 23 instead of adding 3
46
+                if (((char)(text.charAt(i) + shift)  > 'Z' &&
47
+                        text.charAt(i) <= 'Z')
48
+                        || ((char)(text.charAt(i) + shift)  > 'z'
49
+                        && text.charAt(i) <= 'z'))
50
+
51
+                {
52
+                    //add the next character which is encrypted to the String
53
+                    encrypted = encrypted + (char)(text.charAt(i) + shift - 26);
54
+                }
55
+                else
56
+                {
57
+                    //add the next character which is encrypted to the String
58
+                    encrypted = encrypted + (char)(text.charAt(i) + shift);
59
+                }
60
+            }
61
+            else
62
+            {
63
+                //add the original character to the Stringx
64
+                encrypted = encrypted + text.charAt(i);
65
+            }
66
+        }
67
+
68
+        //return the resulting String
69
+        return encrypted;
21 70
     }
22 71
 
23 72
     public String decrypt(String text) {
24
-        return text;
73
+        String decrypted = "";
74
+        for (int i = 0; i < text.length(); i++) {
75
+            if( (text.charAt(i) >= 'A' && text.charAt(i) <= 'Z') ||
76
+                    (text.charAt(i) >= 'a' && text.charAt(i) <= 'z'))
77
+            {
78
+                if (((char)(text.charAt(i) - shift)  < 'A' &&
79
+                        text.charAt(i) >= 'A')
80
+                        || ((char)(text.charAt(i) - shift)  < 'a'
81
+                        && text.charAt(i) >= 'a'))
82
+
83
+                {
84
+                    decrypted = decrypted + (char)(text.charAt(i) - shift + 26);
85
+                }
86
+                else {
87
+                    decrypted = decrypted + (char)(text.charAt(i) - shift);
88
+                }
89
+            }
90
+            else
91
+            {
92
+                decrypted = decrypted + text.charAt(i);
93
+            }
94
+        }
95
+        return decrypted;
25 96
     }
26 97
 
27 98
     public static String rotate(String s, Character c) {
99
+       int shift = c - s.charAt(0);
100
+       return s.substring(shift) + s.substring(0,shift);
101
+    }
102
+
103
+    public String readFile(String fileName){
28 104
 
29
-        return "";
105
+        StringBuilder sb = new StringBuilder();
106
+        // This will reference one line at a time
107
+        String line = null;
108
+
109
+        try {
110
+            // FileReader reads text files in the default encoding.
111
+            FileReader fileReader =
112
+                    new FileReader(fileName);
113
+
114
+            // Always wrap FileReader in BufferedReader.
115
+            BufferedReader bufferedReader =
116
+                    new BufferedReader(fileReader);
117
+
118
+            while((line = bufferedReader.readLine()) != null) {
119
+                sb.append(line + "\n");
120
+            }
121
+
122
+            // Always close files.
123
+            bufferedReader.close();
124
+        }
125
+        catch(FileNotFoundException ex) {
126
+            System.out.println(
127
+                    "Unable to open file '" +
128
+                            fileName + "'");
129
+        }
130
+        catch(IOException ex) {
131
+            System.out.println(
132
+                    "Error reading file '"
133
+                            + fileName + "'");
134
+            // Or we could just do this:
135
+            // ex.printStackTrace();
136
+        }
137
+        return sb.toString();
30 138
     }
31 139
 
140
+    public void encryptFile(String fileName, String newFileName){
141
+        String text = readFile(fileName);
142
+        String encryptedText = encrypt(text);
143
+        writeToFile(newFileName, encryptedText);
144
+    }
145
+
146
+    private void writeToFile(String newFileName, String encryptedText) {
147
+        try {
148
+            FileWriter fileWriter = new FileWriter(newFileName);
149
+            BufferedWriter br = new BufferedWriter(fileWriter);
150
+            br.write(encryptedText);
151
+            br.flush();
152
+            br.close();
153
+        }catch (IOException ie){
154
+            ie.printStackTrace();
155
+        }
156
+    }
32 157
 }

+ 30
- 7
Crypto/src/ROT13Test.java 查看文件

@@ -1,6 +1,9 @@
1
+
2
+import org.junit.Assert;
1 3
 import org.junit.Test;
2 4
 
3
-import static org.junit.Assert.*;
5
+import java.io.*;
6
+
4 7
 
5 8
 public class ROT13Test {
6 9
 
@@ -16,7 +19,7 @@ public class ROT13Test {
16 19
         String actual = cipher.rotate(s1, 'A');
17 20
 
18 21
         // Then
19
-        assertTrue(actual.equals(s2));
22
+        Assert.assertTrue(actual.equals(s2));
20 23
     }
21 24
 
22 25
     @Test
@@ -30,7 +33,7 @@ public class ROT13Test {
30 33
         String actual = cipher.rotate(s1, 'D');
31 34
 
32 35
         // Then
33
-        assertTrue(actual.equals(s2));
36
+        Assert.assertTrue(actual.equals(s2));
34 37
     }
35 38
 
36 39
     @Test
@@ -45,7 +48,7 @@ public class ROT13Test {
45 48
         System.out.println(s1);
46 49
         System.out.println(actual);
47 50
         // Then
48
-        assertTrue(actual.equals(s2));
51
+        Assert.assertTrue(actual.equals(s2));
49 52
     }
50 53
 
51 54
     @Test
@@ -64,14 +67,14 @@ public class ROT13Test {
64 67
         System.out.println(Q1);
65 68
         System.out.println(A1);
66 69
         // Then
67
-        assertTrue(actual.equals(A1));
70
+        Assert.assertTrue(actual.equals(A1));
68 71
 
69 72
         // When
70 73
         String actual2 = cipher.decrypt(Q2);
71 74
         System.out.println(Q2);
72 75
         System.out.println(A2);
73 76
         // Then
74
-        assertTrue(actual2.equals(A2));
77
+        Assert.assertTrue(actual2.equals(A2));
75 78
     }
76 79
     @Test
77 80
     public void cryptTest2() {
@@ -85,7 +88,27 @@ public class ROT13Test {
85 88
         String actual = cipher.crypt(cipher.crypt(Q1));
86 89
         System.out.println(actual);
87 90
         // Then
88
-        assertTrue(actual.equals(Q1));
91
+        Assert.assertTrue(actual.equals(Q1));
92
+    }
93
+
94
+    @Test
95
+    public void testFileEncryption() throws IOException {
96
+        ROT13 cipher = new ROT13('a', 'n');
97
+        String fileName = "sonnet18.txt";
98
+        String encryptedFile = "encryptedFile.txt";
99
+        String line;
100
+        String newFileText ="";
101
+
102
+        cipher.encryptFile(fileName, encryptedFile);
103
+        String encryptedText = cipher.encrypt(cipher.readFile(fileName));
104
+
105
+        FileReader fr = new FileReader(encryptedFile);
106
+        BufferedReader br = new BufferedReader(fr);
107
+        while((line = br.readLine())!= null){
108
+            newFileText += line + "\n";
109
+        }
110
+
111
+        Assert.assertEquals(encryptedText, newFileText);
89 112
     }
90 113
 
91 114
 }

+ 15
- 0
SimpleCrypt.iml 查看文件

@@ -0,0 +1,15 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
3
+  <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
4
+    <output url="file://$MODULE_DIR$/target/classes" />
5
+    <output-test url="file://$MODULE_DIR$/target/test-classes" />
6
+    <content url="file://$MODULE_DIR$">
7
+      <sourceFolder url="file://$MODULE_DIR$/Crypto/src" isTestSource="false" />
8
+      <excludeFolder url="file://$MODULE_DIR$/target" />
9
+    </content>
10
+    <orderEntry type="inheritedJdk" />
11
+    <orderEntry type="sourceFolder" forTests="false" />
12
+    <orderEntry type="library" name="Maven: junit:junit:4.12" level="project" />
13
+    <orderEntry type="library" name="Maven: org.hamcrest:hamcrest-core:1.3" level="project" />
14
+  </component>
15
+</module>

+ 14
- 0
encryptedFile.txt 查看文件

@@ -0,0 +1,14 @@
1
+Funyy V pbzcner gurr gb n fhzzre’f qnl?
2
+Gubh neg zber ybiryl naq zber grzcrengr:
3
+Ebhtu jvaqf qb funxr gur qneyvat ohqf bs Znl,
4
+Naq fhzzre’f yrnfr ungu nyy gbb fubeg n qngr;
5
+Fbzrgvzr gbb ubg gur rlr bs urnira fuvarf,
6
+Naq bsgra vf uvf tbyq pbzcyrkvba qvzz'q;
7
+Naq rirel snve sebz snve fbzrgvzr qrpyvarf,
8
+Ol punapr be angher’f punatvat pbhefr hagevzz'q;
9
+Ohg gul rgreany fhzzre funyy abg snqr,
10
+Abe ybfr cbffrffvba bs gung snve gubh bj’fg;
11
+Abe funyy qrngu oent gubh jnaqre’fg va uvf funqr,
12
+Jura va rgreany yvarf gb gvzr gubh tebj’fg:
13
+   Fb ybat nf zra pna oerngur be rlrf pna frr,
14
+   Fb ybat yvirf guvf, naq guvf tvirf yvsr gb gurr.

+ 26
- 0
pom.xml 查看文件

@@ -8,5 +8,31 @@
8 8
     <artifactId>SimpleCrypt</artifactId>
9 9
     <version>1.0-SNAPSHOT</version>
10 10
 
11
+    <build>
12
+        <plugins>
13
+            <plugin>
14
+                <groupId>org.apache.maven.plugins</groupId>
15
+                <artifactId>maven-compiler-plugin</artifactId>
16
+                <configuration>
17
+                    <source>8</source>
18
+                    <target>8</target>
19
+                </configuration>
20
+            </plugin>
21
+        </plugins>
22
+    </build>
23
+    <dependencies>
24
+        <dependency>
25
+            <groupId>junit</groupId>
26
+            <artifactId>junit</artifactId>
27
+            <version>4.12</version>
28
+            <scope>test</scope>
29
+        </dependency>
30
+        <dependency>
31
+            <groupId>junit</groupId>
32
+            <artifactId>junit</artifactId>
33
+            <version>4.12</version>
34
+        </dependency>
35
+
36
+    </dependencies>
11 37
 
12 38
 </project>