bouncy castle pgp - PartialInputStream中流的过早结束

时间:2018-02-19 16:16:54

标签: java encryption cryptography bouncycastle

我正在使用充气城堡pgp和bouncy-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)

我没有使用任何字符串转换,所以我无法理解为什么字节数组长度存在问题

1 个答案:

答案 0 :(得分:0)

确实你必须关闭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使用了“尝试使用资源”&#39;它会自动关闭流。我澄清了项目中的README,以使其更加清晰。