-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPicTest.java
More file actions
100 lines (88 loc) · 2.74 KB
/
Copy pathPicTest.java
File metadata and controls
100 lines (88 loc) · 2.74 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package tutorial.java;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class PicTest {
/* encrypt a picture file*/
@Test
public void test() {
FileInputStream fis =null;
FileOutputStream fos =null;
try {
fis = new FileInputStream("nature.jpg");
fos = new FileOutputStream("nature_encrypt.jpg");
// read the file
int len;
byte[] buffer = new byte[10];
while ( (len = fis.read(buffer)) != -1){
/* wrong method
// this method doesn't encrypt buffer at all, just assign
// the encrypt byte to another var b; 从buffer中取出直接付给了新的变量b
for(byte b : buffer){
b = (byte) (b ^ 5);
}
*/
// syco each byte
for(int i = 0; i < len; i++){
buffer[i] = (byte) (buffer[i] ^ 5); // encryption
}
fos.write(buffer, 0, len);
}
}catch (IOException e){
e.printStackTrace();
}finally {
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/* decrypt an encrypted picture file*/
@Test
public void test2() {
FileInputStream fis =null;
FileOutputStream fos =null;
try {
fis = new FileInputStream("nature_encrypt.jpg");
fos = new FileOutputStream("nature_decrypt.jpg");
// read the file
int len;
byte[] buffer = new byte[10];
while ( (len = fis.read(buffer)) != -1){
// syco each byte
for(int i = 0; i < len; i++){
buffer[i] = (byte) (buffer[i] ^ 5); // decryption
}
fos.write(buffer, 0, len);
}
}catch (IOException e){
e.printStackTrace();
}finally {
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}