IO流传输中的图片加密 IO流传输中的图片加密

这是我参与更文挑战的第7天,活动详情查看: 更文挑战

IO流传输中的图片加密

1.加密过程

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
js复制代码package 图片加密_2020;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class PicTest {
public static void main(String[] args) {
FileInputStream fis=null;
FileOutputStream fos=null;
try {
fis = new FileInputStream(new File("怪物万岁.png"));
fos = new FileOutputStream("怪物万岁(加密).png");

byte[] buffer = new byte[20];
int len;
while ((len = fis.read(buffer)) != -1) {
for (int i = 0; i < len; i++) {
buffer[i] = (byte) (buffer[i] ^ 5);
}
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
}
}
1
2
js复制代码            fis = new FileInputStream(new File("怪物万岁.png"));
fos = new FileOutputStream("怪物万岁(加密).png");

fis接收需要加密的图片文件
fos存放加密后文件

1
2
3
4
5
6
js复制代码 while ((len = fis.read(buffer)) != -1) {
for (int i = 0; i < len; i++) {
buffer[i] = (byte) (buffer[i] ^ 5);
}
fos.write(buffer, 0, len);
}

buffer[i] = (byte) (buffer[i] ^ 5);
关键加密步骤,将buffer中的每一位与5或其他数字异或操作,不经解密程序的操作,得到的图片将不能正常打开。

image.png

2.解密操作

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
js复制代码package 图片加密_2020;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class jiemi {
public static void main(String[] args) {
FileInputStream fis=null;
FileOutputStream fos=null;
try {
fis = new FileInputStream(new File("怪物万岁(加密).png"));
fos = new FileOutputStream("怪物万岁(解密后).png");

byte[] buffer = new byte[20];
int len;
while ((len = fis.read(buffer)) != -1) {
for (int i = 0; i < len; i++) {
buffer[i] = (byte) (buffer[i] ^ 5);
}
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

}
}
1
2
js复制代码            fis = new FileInputStream(new File("怪物万岁(加密).png"));
fos = new FileOutputStream("怪物万岁(解密后).png");

fis接收加密后的文件
fos则存放解密后的图片文件

1
2
3
js复制代码  for (int i = 0; i < len; i++) {
buffer[i] = (byte) (buffer[i] ^ 5);
}

其中,解密操作再次异或5,根据异或操作的特性可以得到正常的图片内容。

image.png

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%