我正在开发一个 iPad 应用程序并使用 RNCryptor 在设备上进行加密和解密。此加密格式有一个 Java 版本,形式为 JNCryptor .
我现在要从 InputStream 读取数据,但我想在读取数据之前对其进行加密。我找到了一个名为 CipherInputStream 的类,这似乎正是我正在寻找的。唯一的问题是,我需要一个 Cipher (和 Provider )来指定加密方法,但我不知道该怎么做。是否可以定义自定义提供程序?
有人对使用 JNCryptor 加密输入流的替代方法有建议吗?
最佳答案
最后我编写了一个类来读取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();
...
}
}
}
关于java - 如何使用 JNCryptor 加密输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15905845/