在我最后写一个类来读取的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();
...
}
}
}
我会,谢谢:) 现在我写了自己的代码,但如果像我可以调用的“更新”方法,而不是必须做所有事情,那将是很好的。我认为我现在可以使用的图书馆唯一的方法是用于代码生成,哈哈。 我已经在这个问题的答案中发布了我的解决方案,您可能可以使用它:) – Johanneke 2013-04-16 13:11:55