我正在使用充气城堡pgp和充气gpg(https://github.com/neuhalje/bouncy-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();
}


自述文件中的example使用了“ try-with-resources”,它会自动关闭流。我在项目中阐明了自述文件,以使其更加清楚。

07-26 08:35