我正在使用弹力城堡PGP和弹力GPG(https://github.com/neuhalje/boncy-gpg(,我正在尝试做非常简单的事情:
ByteArrayOutputStream cryptoBytes = new ByteArrayOutputStream();
try {
final OutputStream outputStream = BouncyGPG
.encryptToStream()
.withConfig(keyringConfig)
.withStrongAlgorithms()
.toRecipient(recipient)
.andDoNotSign()
.binaryOutput()
.andWriteTo(cryptoBytes);
Streams.pipeAll(input, outputStream);
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
}
ByteArrayOutputStream plainBytes = new ByteArrayOutputStream();
try {
final InputStream plaintextStream = BouncyGPG
.decryptAndVerifyStream()
.withConfig(keyringConfig)
.andIgnoreSignatures()
.fromEncryptedInputStream(new ByteArrayInputStream(cryptoBytes.toByteArray()));
Streams.pipeAll(plaintextStream, plainBytes);
} catch (Exception e) {
e.printStackTrace();
}
但是我有一个例外试图解密:
java.io.EOFException: premature end of stream in PartialInputStream
at org.bouncycastle.bcpg.BCPGInputStream$PartialInputStream.read(Unknown Source)
at org.bouncycastle.bcpg.BCPGInputStream.read(Unknown Source)
at org.bouncycastle.bcpg.SymmetricEncIntegrityPacket.<init>(Unknown Source)
我不使用任何字符串转换,所以我不明白为什么字节数组长度有问题
确实您必须关闭OutputStream
。原因是GPG在流的末端写下签名。这是通过关闭流来触发的。
try {
final OutputStream outputStream = BouncyGPG
.encryptToStream()
.withConfig(keyringConfig)
.withStrongAlgorithms()
.toRecipient(recipient)
.andDoNotSign()
.binaryOutput()
.andWriteTo(cryptoBytes);
Streams.pipeAll(input, outputStream);
outputStream.close(); // <<<----
} catch (Exception e) {
e.printStackTrace();
}
读书中的示例使用了自动关闭流的" try-with-with-resources"。我澄清了项目中的读书文件,以使其更加清楚。