最后,我编写了一个类来读取 InputStream,一次加密数据部分,然后写入 PipedOutputStream。然后我将这个 PipedOutputStream 连接到一个 PipedInputStream,我最终返回了它。PipedOutputStream 的加密和写入发生在单独的线程上,以避免死锁。
PipedInputStream pin = new PipedInputStream();
PipedOutputStream pout = new PipedOutputStream(pin);
EncryptionPipe pipe = new EncryptionPipe(5, pout, in, cipher, mac, metaData);
//EncryptionPipe(int interval, OutputStream out, InputStream in
// ,Cipher cipher, Mac mac, byte[] metaData)
pipe.start();
return pin;
在 EncryptionPipe 中:
public class EncryptionPipe extends Thread {
...
@Override
public void run() {
try {
mac.update(metaData);
out.write(metaData);
byte[] buf = new byte[1024];
int bytesRead = 0;
byte[] crypted;
byte[] hmac;
while ((bytesRead = in.read(buf)) != -1) {
if (bytesRead < buf.length) {
//the doFinal methods add padding if necessary, important detail!
crypted = cipher.doFinal(buf, 0, bytesRead);
hmac = mac.doFinal(crypted);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bytes.write(crypted);
bytes.write(hmac);
crypted = bytes.toByteArray();
bytesRead = crypted.length;
bytes.close();
} else {
crypted = cipher.update(buf, 0, bytesRead);
mac.update(crypted, 0, bytesRead);
}
out.write(crypted, 0, bytesRead);
synchronized (this) {
this.wait(interval);
}
}
out.close();
...
}
}
}