我正在尝试实施简单的加密聊天;顺便说一句,我在使用包装器时遇到了问题。
Cypher类运行良好,它(de)加密单字节。
另外,我有CypherOutputStream
和CypherInputStream
类,分别扩展FilterOutputStream
和FilterInputStream
。它们单独运行很好,但当我尝试将CypherInputStream
包裹在BufferedReader
(或Scanner
)周围时,它只是停止尝试读取数据。
具体来说,调试代码时,BufferedReader
对象似乎正确地调用了CypherInputStream
对象读取。然后,它读取整个字(逐字节),但它无法正确读取行尾(然后停止读取);所以,它继续调用CypherInputStream read()
,期待一个新的字节。有任何想法吗?
在此先感谢:)
以下是CypherInputStream
:
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public class CypherInputStream extends FilterInputStream
{
private Cypher cypher;
public CypherInputStream(InputStream in, Cypher c)
{
super(in);
cypher = c;
}
@Override
public int read() throws IOException
{
return cypher.decrypt((byte) in.read(););
}
@Override
public int read(byte[] data, int off, int len) throws IOException
{
int i = -1;
for (i = off; i < off + len; i++)
data[i] = (byte) this.read();
return i - off;
}
@Override
public int read(byte[] data) throws IOException
{
return this.read(data, 0, data.length);
}
}
下面,您可以看到处理聊天通信的CryptedChatHandler
对象的主要代码行。
BufferedWriter userToSocket = new BufferedWriter(new OutputStreamWriter(
new CypherOutputStream(socket.getOutputStream(), cypher)));
BufferedReader socketToUser = new BufferedReader(new InputStreamReader(
new CypherInputStream(socket.getInputStream(), cypher)));
...
while (status == YOU)
if (inFromUser.hasNextLine())
String s = inFromUser.nextLine();
userToSocket.write(s.concat("\r\n"));
...
while (status == OTHER)
String s = socketToUser.readLine();
System.out.print(s);