设计思路
- 继承合适的流类:
MyCipherInputStream
继承自FilterInputStream
,MyCipherOutputStream
继承自FilterOutputStream
。这样可以在已有流功能的基础上添加加密和解密逻辑。
- 加密和解密逻辑:采用异或加密,通过一个固定的密钥与数据进行异或操作。
- 构造函数:接受一个底层流作为参数,以便在构造时关联底层流。
核心代码实现
MyCipherInputStream
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public class MyCipherInputStream extends FilterInputStream {
private static final byte KEY = 0x42; // 固定密钥
public MyCipherInputStream(InputStream in) {
super(in);
}
@Override
public int read() throws IOException {
int data = super.read();
if (data != -1) {
return data ^ KEY;
}
return data;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int readBytes = super.read(b, off, len);
if (readBytes > 0) {
for (int i = 0; i < readBytes; i++) {
b[off + i] = (byte) (b[off + i] ^ KEY);
}
}
return readBytes;
}
}
MyCipherOutputStream
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class MyCipherOutputStream extends FilterOutputStream {
private static final byte KEY = 0x42; // 固定密钥
public MyCipherOutputStream(OutputStream out) {
super(out);
}
@Override
public void write(int b) throws IOException {
super.write(b ^ KEY);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
byte[] encrypted = new byte[len];
for (int i = 0; i < len; i++) {
encrypted[i] = (byte) (b[off + i] ^ KEY);
}
super.write(encrypted, 0, len);
}
}